当我使用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
我做错了什么?
答案 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
}