我写了一些代码来读取文本文件并返回一个数组,每行存储在一个元素中。我不能为我的生活找出为什么这不起作用......任何人都可以快速浏览一下吗? System.out.println(行)的输出;是空的,所以我猜测读取线路时出现问题,但我看不出为什么。顺便说一句,我传递给它的文件肯定有一些内容!阅读Java中的文本文件
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
}
你确定你已经有文件了吗?你是否在正确的位置查找文件(相对于用户导演)? – 2011-12-31 13:23:26
file/br/bw在哪里声明? InOutSys和readFile是公开的,但第二个关闭br。如何避免在封闭的br上调用readFile? – 2011-12-31 13:38:35
文件的位置。 – javaDisciple 2011-12-31 13:40:29