我在这里检查了很多关于stackoverflow的不同主题,但到目前为止找不到任何有用的方法:/
所以这是我的问题。我正在写文件复印机。在读取文件时已经出现问题。我的测试文档有3行随机文本。所有这三行都应写入字符串数组中。问题是只有textdocument的第二行被写入数组,而我不知道为什么。已经调试过了,但是没有进一步了解我。
我知道具有不同类的文件复印机有不同的解决方案。但是我真的很想让它与我在这里使用的类一起运行。
String[] array = new String[5];
String datei = "test.txt";
public String[] readfile() throws FileNotFoundException {
FileReader fr = new FileReader(datei);
BufferedReader bf = new BufferedReader(fr);
try {
int i=0;
//String Zeile = bf.readLine();
while(bf.readLine() != null){
array[i] = bf.readLine();
// System.out.println(array[i]); This line is for testing
i++;
}
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
return array;
最佳答案
对于循环的每次迭代,您都要调用readLine()
两次,从而丢弃其他所有行。您需要捕获每次对readLine()
的调用返回的值,因为每个readLine()
调用都会提高读者在文件中的位置。
这是idiomatic解决方案:
String line;
while((line = bf.readLine()) != null){
array[i] = line;
i++;
}