我现在遇到了一个有趣的问题。
我正在尝试在 java 中读取此文件,其中包含按字母顺序排列的 1000 个最常见的英语单词:
http://www.file-upload.net/download-6679295/basicVocabulary.txt.html
这是文件开头的片段:
a
able
about
above
according
account
across
act
action
added
afraid
after
我现在的问题是,虽然看起来我正在正确读取 txt 文件,但稍后在我的结果集/结果列表中缺少第一行。在这种情况下,这是字母“a”,因为它位于第一个位置。
为了让您能够重现我的问题,请使用上面的 txt 文件尝试此示例代码并亲自查看(不要忘记更新文件路径)。我在评论中添加了为我准备的控制台输出。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MyWrongBehaviour {
public static void main(String[] args){
MyWrongBehaviour wrong = new MyWrongBehaviour();
List<String> list = wrong.loadLanguageFile();
System.out.println("size of the list: " + list.size()); //Answer is 1000, that's the correct size
for(String s : list){
System.out.println(s); // "a" will appear, so it is somehow included
}
if(list.contains("a")){
System.out.println("found \"a\""); // doesn't get written on the console, can't find it
}
for(String s : list){
if(s.equals("a")){
System.out.println("found \"a\""); // never gets written, can't find it
}
}
}
private List<String> loadLanguageFile() {
List<String> result = null;
try (InputStream vocIn = getClass().getResourceAsStream(
"/test/basicVocabulary.txt")) {
if (vocIn == null) {
throw new IllegalStateException(
"InputStream for the basic vocabulary must not be null");
}
BufferedReader in = new BufferedReader(new InputStreamReader(vocIn,
"UTF-8"));
String zeile = null;
result = new ArrayList<>();
while ((zeile = in.readLine()) != null) {
result.add(zeile.trim());
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
有人知道为什么会发生这种情况以及我可以做些什么来解决它吗?我的想法是可能存在字符集错误,尽管我将文件保存为 UTF-8,或者不知何故有一个不可见的字符损坏了文件,但我不知道如何识别它。
顺便说一句:我以前使用过 Hashset,但使用 Set 时甚至没有添加第一行。现在它被添加了,但找不到它。
感谢您的每一个回答,并认为您是在与我分享。
最佳答案
文件以 byte-order mark 开头这表明它是 UTF-8,所以第一行实际上等同于“\ufeffa”(即两个字符,U+FEFF,然后是 'a'),然后 不等于“一个”。
剥离它的一种方法是使用:
result.add(zeile.trim().replace("\ufeff", ""));
更改后,您的代码将按预期工作。在 Java 中可能有更好的删除字节顺序标记的方法,但我不知道。
关于java - 在 java 中读取文本文件的问题 - 尽管存在但结果列表中缺少行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12820598/