尽管存在,但在结果列表中缺少在java中读取文本文件的问题

Way*_*der 1 java file-io inputstream file character-encoding

我现在遇到一个有趣的问题.

我正在尝试在java中读取此文件,其中包含按字母顺序排列的1000个最常见的英语单词:

http://www.file-upload.net/download-6679295/basicVocabulary.txt.html

这是文件开头的片段:

a
able
about
above
according
account
across
act
action
added
afraid
after
Run Code Online (Sandbox Code Playgroud)

我现在的问题是,虽然看起来我正在正确读取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;
}


}
Run Code Online (Sandbox Code Playgroud)

有人知道为什么会这样,我能做些什么来解决它?我的想法是,可能存在charset错误,虽然我将文件保存为UTF-8,或者某种程度上有一个不可见的字符会破坏文件,但我不知道如何识别它.

顺便说一下:我之前使用过Hashset,但是使用Set第一行甚至没有添加.现在它被添加,但找不到它.

感谢您的每一个回答,并认为您与我分享.

Jon*_*eet 9

该文件以字节顺序标记开头,表示它是UTF-8,因此第一行实际上等同于"\ ufeffa"(即两个字符,U + FEFF然后是'a'),然后它们相等到"一个".

剥离这种方法的一种方法就是使用:

result.add(zeile.trim().replace("\ufeff", ""));
Run Code Online (Sandbox Code Playgroud)

在更改之后,您的代码按预期工作.可能有一种更好的方法来删除Java中的字节顺序标记,但我不知道它是否随便.