【发布时间】:2014-12-13 19:40:55
【问题描述】:
因为我每次做项目都懒得重写文件管理器,所以我在做一个文件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());
}
}
}
【问题讨论】:
-
请不要重新发明轮子——没有人需要方轮。尤其是没有一个缓慢穿刺的。只需使用
Files实用程序类。
标签: java io bufferedreader