在下面的代码中,我尝试读取具有特定长度的行并在另一个记事本上写入。这种编码对英文字符很有效。但是对于泰米尔字母,如果我试着数数…它的计数为:
(如)தமிழ்
计数为5…(即)",",","one_answers"。但我想把它算作3","மி"one_answers"ழ்"
我想将此逻辑应用于文本文件....中的多个单词
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class ii {
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br =null;
FileWriter fw=null;
BufferedWriter bw=null;
String [] stringArray;
int counLine = 0;
int arrayLength ;
String s="";
String stringLine="";
try{
fr = new FileReader("F:\New folder (2)\N.txt");
fw=new FileWriter("F:\New folder (2)\o.txt");
br = new BufferedReader(fr);
bw=new BufferedWriter(fw);
while((s = br.readLine()) != null){
stringLine = stringLine + s;
stringLine = stringLine + " ";
counLine ++;
}
stringArray = stringLine.split(" ");
arrayLength = stringArray.length;
for (int i = 0; i < arrayLength; i++) {
int c = 1 ;
for (int j = i+1; j < arrayLength; j++) {
if(stringArray[i].equalsIgnoreCase(stringArray[j])){
c++;
for (int j2 = j; j2 < arrayLength; j2++)
{
}}
int k;
for(k=2;k==stringArray[i].length();i++)
{
bw.write(stringArray[i]);
bw.newLine();
}}} fr.close();
br.close();
bw.flush();
bw.close();
}catch (Exception e) {
e.printStackTrace();
}}}
一种方法是使用BreakIterator遍历字符,并自己计数。(未测试的代码)
int characterCount = 0;
BreakIterator iterator = BreakIterator.getCharacterInstance();
iterator.setText("தமிழ்");
int boundary = iterator.first();
while (boundary != BreakIterator.DONE) {
characterCount++;
boundary = iterator.next();
}
参见http://docs.oracle.com/javase/tutorial/i18n/text/char.html
这基本上是由于编码问题,所以,首先按照以下步骤更改java项目的文本文件编码
右键单击您的项目名称=>选择属性=>选择资源=>文本文件编码=>选择其他并选择UTF- 8作为编码,
记事本默认不支持UTF字符。相反,它支持ANSI。然而,你的问题不是由于这个。
你的程序应该知道它在读取或写入时将使用什么编码。没有魔法。您需要设置编码(例如- UTF8)。FileReader的结构采用默认的平台编码,这显然不适合你。
我猜你需要-
Reader reader = new InputStreamReader(new FileInputStream("c:/foo.txt"), "UTF-8");
读取和写入UTF - 8(不同语言)字符的文件
这是因为字符串计数unicode标记和unicode字母。要忽略unicode标记,可以使用以下正则表达式
import java.util.regex.*;
......
String word = "தமிழ்";
String regex = "[^u0bbe-u0bcd.]";
Pattern r = Pattern.compile(regex);
Matcher m = r.matcher(word);
int count=0;
while (m.find())count++;
System.out.print(count);