因为懒得每次做项目都重写文件管理器,所以就做一个文件IO库。当我运行它时,我得到:
null
null
null
它查找文件中有多少行,但将它们全部设置为空。我该如何解决这个问题?
文件管理器:
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class KezelFile {
private String path;
BufferedReader buff;
public KezelFile(String filePath) throws IOException {
path = filePath;
openFile();
}
public void openFile() throws IOException {
FileReader read = new FileReader(path);
buff = new BufferedReader(read);
}
public String[] toStringArray() throws IOException {
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++) {
textData[i] = buff.readLine();
}
return textData;
}
int readLines() throws IOException {
String lines;
int noLines = 0;
while ((lines = buff.readLine()) != null) {
noLines++;
}
return noLines;
}
public void closeFile() throws IOException {
buff.close();
}
}
主类:
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args) throws IOException {
String filePath = "C:/test.txt";
try {
KezelFile file = new KezelFile(filePath);
String[] aryLines = file.toStringArray();
int i;
for (i=0; i < aryLines.length; i++) {
System.out.println(aryLines[i]);
}
file.closeFile();
}
catch (IOException error){
System.out.println(error.getMessage());
}
}
}
最佳答案
读取完所有行后,您将无法再次读取这些行,直到再次打开文件。只是因为 readLine() 是从不同的方法调用的,所以它不会“重置”阅读器。
更好的解决方案是只读取文件一次。我建议您将这些行读入 List<String>
或者甚至在您阅读文件时更好地处理该文件,并且您也不需要该集合。
顺便说一句,在 Java 8 中你可以这样写
Files.lines(filename).forEach(System.out::println);
也许是时候尝试 Java8 了;)
关于java - 文件读取器库输出 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27462870/