我必须准备一个.txt文件,并计算文件中每个字母字符出现的次数。我发现了一段非常好的代码,但不幸的是,它不适用于波兰字符,如ą,ę,ć,ó,ż,ź。即使我把它们放在数组中,由于某种原因它们在.txt文件中找不到,所以输出为0.
有谁知道为什么?也许我应该用不同的方式来计算它们,使用“Switch”或类似的东西。 在有人问之前 - 是的,.txt文件是用UTF-8保存的:)
public static void main(String[] args) throws FileNotFoundException {
int ch;
BufferedReader reader;
try {
int counter = 0;
for (char a : "AĄĆĘÓBCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray()) {
reader = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\pan.txt"));
char toSearch = a;
counter = 0;
try {
while ((ch = reader.read()) != -1) {
if (a == Character.toUpperCase((char) ch)) {
counter++;
}
}
} catch (IOException e) {
System.out.println("Error");
e.printStackTrace();
}
System.out.println(toSearch + " occurs " + counter);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
答案 0 :(得分:3)
您的问题与编码和默认系统charset
相关尝试将读者变量更改为此
InputStreamReader reader = new InputStreamReader(new FileInputStream("C:\\Users\\User\\Desktop\\pan.txt"), "UTF-8");
答案 1 :(得分:0)
试试这个: 我建议您使用NIO和我为您编写的代码,使用更快的NIO,RandomAccessFile和MappedByteBuffer:
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
public class FileReadNio
{
public static void main(String[] args) throws IOException
{
Map<Character, Integer> charCountMap = new HashMap<>();
RandomAccessFile rndFile = new RandomAccessFile
("c:\\test123.txt", "r");
FileChannel inChannel = rndFile.getChannel();
MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
buffer.load();
for (int i = 0; i < buffer.limit(); i++)
{
char c = (char) buffer.get();
if (charCountMap.get(c) != null) {
int cnt = charCountMap.get(c);
charCountMap.put(c, ++cnt);
}
else
{
charCountMap.put(c, 1);
}
}
for (Map.Entry<Character,Integer> characterIntegerEntry : charCountMap.entrySet()) {
System.out.printf("char: %s :: count=%d", characterIntegerEntry.getKey(), characterIntegerEntry.getValue());
System.out.println();
}
buffer.clear();
inChannel.close();
rndFile.close();
}
}