我不得不承认我并不是编码等方面的真正专家。我有以下问题:我的程序必须读取一个文本文件,其中不仅包含 std. ASCII 但“特殊字符和语言”,如 "..офіціалнов назвов Російска.."
所以我们假设这是文件的内容:офіціалнов назвов Російска
现在我想将整个文件内容分成单个单词并创建另一个文件,将所有这些单词按如下行列出:
офіціалнов
назвов
Російска
我的问题是:如果我将这些单个单词放入 HashMap 并从中读取值 -> 编码丢失。这是我的代码:
final StringBuffer fileData = new StringBuffer(1000);
final BufferedReader reader = new BufferedReader(
new FileReader("fileIn.txt"));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1)
{
final String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
String mergedContent = fileData.toString();
mergedContent = mergedContent.replaceAll("\\<.*?>", " ");
mergedContent = mergedContent.replaceAll("\\r\\n|\\r|\\n", " ");
final BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("fileOut.txt")));
final HashMap<String, String> wordsMap = new HashMap<String, String>();
final String test[] = mergedContent.split(" ");
for (final String string : test)
{
wordsMap.put(string, string);
}
for (final String string : wordsMap.values())
{
out.write(string + "\n");
}
out.close();
这个片段破坏了编码器。有趣的是:如果我不将值放入 HashMap,而是立即将它们存储到输出文件中,例如:
...
for (final String string : test)
{
out.write(string + "\n");
//wordsMap.put(string, string);
}
//for (final String string : wordsMap.values())
//{
// out.write(string + "\n");
//}
out.close();
...然后它会像我预期的那样工作。
我做错了什么?
最佳答案
尝试使用 new InputStreamReader(new FileInputStream(file), "UTF-8")
然后对输出进行同样的操作。并确保您的文件以 UTF-8 编码
hashmap 不可能对编码做任何事情。
关于java - HashMap破坏编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8427488/