【问题标题】:Java BufferedReader not reading file contentsJava BufferedReader 不读取文件内容
【发布时间】: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 存在吗?
  • 你试过"UTF-8" with a hyphen吗?
  • @JacobG。使用调试菜单,我可以验证该文件是否存在。
  • @rgettman 我添加了连字符并没有改变结果

标签: java xml


【解决方案1】:

得到 null 作为响应很可能是因为您的编码错误。我注意到你有“UTF8”,不应该是“UTF-8”还是 StandardCharsets.UTF_8.name()?

【讨论】:

  • 我发现连字符或者没有连字符,功能都一样
【解决方案2】:

我设法找出了问题所在。在较早的运行中,程序必须删除第一个文件,所以当代码试图读取它时,它是空的。此解决方案有效,@Sudhakar 的解决方案也有效。

【讨论】:

    【解决方案3】:

    您可以尝试下面的代码来读取文件内容。

    public static List<String> getFileContentAsList(String fileName) {
        File f = new File(fileName);
        try {
            return Files.readAllLines(f.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return Collections.emptyList();
    }   
    

    【讨论】:

    • 对我来说,该代码返回了一个空列表,类似于我上面的内容。
    猜你喜欢
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多