如何在JAVA LIST中存储第一行文本文件

时间:2015-10-20 05:39:28

标签: java

当我使用list.get(0)时,我不知道我的代码应该显示我的文本文件的第一行出了什么问题,但我总是得到第二行!!

String everything;
ArrayList<String> list = new ArrayList<String>();

try(BufferedReader br = new BufferedReader(new FileReader("lol/new.txt"))) {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
        list.add(line);
    }

    everything = sb.toString(); // maybe I'll need this :D 
}

FILE.TXT

10 10
5 5 N
DADADADAA

当我做一个简单的System.out.println(list.get(0));时,我得到5 5 N而不是10 10我做错了什么?

4 个答案:

答案 0 :(得分:2)

问题是在while循环之外你已经拉出第一行并且在while循环的迭代中,你从不使用你拉的第一行。

尝试在while循环结束时拉下一行,然后使用在while循环之前拉出的line

while (line != null) {
    sb.append(line);
    sb.append(System.lineSeparator());
    list.add(line);
    line = br.readLine();
}

答案 1 :(得分:1)

试试这个

    String everything;
    ArrayList<String> list = new ArrayList<String>();

    try(BufferedReader br = new BufferedReader(new FileReader("lol/new.txt"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine(); // Read first line

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            list.add(line); // Line order has changed!
            line = br.readLine(); // Read next line
        }
        everything = sb.toString(); // maybe I'll need this :D 

    }

答案 2 :(得分:1)

请参阅我对代码的评论

    String everything;
    ArrayList<String> list = new ArrayList<String>();

    try(BufferedReader br = new BufferedReader(new FileReader("lol/new.txt"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            //up to this point variable line has the line number 1
            //first line is overwritten with line number 2
            line = br.readLine();
            //when you add the line to your ArrayList, line variable contains the second line
            list.add(line);
        }
        everything = sb.toString();

    }

答案 3 :(得分:1)

检查代码中的注释。

    String everything;
    ArrayList<String> list = new ArrayList<String>();

    try(BufferedReader br = new BufferedReader(new FileReader("lol/new.txt"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine(); // You read first line of file
                                     // which is discarded.

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine(); // You read second, and the rest of lines of file.
                                  // First line is discarded here.
            list.add(line);       // Add to list.
        }
        everything = sb.toString(); // maybe I'll need this :D 

    }