【发布时间】:2011-12-31 13:20:20
【问题描述】:
我编写了一些代码来读取文本文件并返回一个数组,其中每一行都存储在一个元素中。我一生都无法弄清楚为什么这不起作用……有人可以快速浏览一下吗? System.out.println(line) 的输出;是空的,所以我猜在读取该行时有问题,但我不明白为什么。顺便说一句,我传递给它的文件肯定有东西!
public InOutSys(String filename) {
try {
file = new File(filename);
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file));
} catch (Exception e) {
e.printStackTrace();
}
}
public String[] readFile() {
ArrayList<String> dataList = new ArrayList<String>(); // use ArrayList because it can expand automatically
try {
String line;
// Read in lines of the document until you read a null line
do {
line = br.readLine();
System.out.println(line);
dataList.add(line);
} while (line != null && !line.isEmpty());
br.close();
} catch (Exception e) {
e.printStackTrace();
}
// Convert the ArrayList into an Array
String[] dataArr = new String[dataList.size()];
dataArr = dataList.toArray(dataArr);
// Test
for (String s : dataArr)
System.out.println(s);
return dataArr; // Returns an array containing the separate lines of the
// file
}
【问题讨论】:
-
你确定你的文件没问题吗?您是否在正确的位置(相对于用户主管)寻找文件?
-
file/br/bw 在哪里声明? InOutSys 和 readFile 是公开的,但第二个关闭 br。如何避免在关闭的 br 上调用 readFile?
标签: java bufferedreader