【发布时间】:2018-05-21 16:58:53
【问题描述】:
我目前正在尝试创建一个程序来读取和修改 .test 文件(UTF-8,看起来类似于 xml 文件)以避免手动编辑每个文件。我设法让程序成功地遍历文件夹中的文件,但是当我试图读取文件的内容时出现了问题。目前我的 readFile 函数如下所示:
public static ArrayList<String> readFile(String fileName) {
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
File file = new File(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
// Create arrayList to return
ArrayList<String> fileContents = new ArrayList<String>();
// Read first line
line = reader.readLine();
// Loop through file, and write each line to arrayList
while(line != null) {
fileContents.add(line);
line = reader.readLine();
}
// Close reader
reader.close();
// Return file contents
return fileContents;
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
return null;
}
其中 fileName 是带有文件路径的字符串(例如:c:\Tests\test1.test)。
我尝试过使用 PrintReader,但也没有用。代码没有抛出异常,当我读取第一行(line = reader.readLine())时,阅读器返回null,就好像文件为空一样。我是否错误地使用了阅读器?
任何帮助或见解将不胜感激。谢谢!
【问题讨论】:
-
你能验证
file存在吗? -
@JacobG。使用调试菜单,我可以验证该文件是否存在。
-
@rgettman 我添加了连字符并没有改变结果