【问题标题】:Unable to read a Java file in a program无法在程序中读取 Java 文件
【发布时间】:2016-10-12 20:22:11
【问题描述】:

我创建了一个读取文件并在输出中显示相同内容的 Java 程序。但是我的输出就像无法打开文件 test.txt 一样。有什么帮助吗?

package test;
import java.io.*;

public class Test {

    public static void main(String[] args) {
        // The name of the file to open.
        String fileName = "test.txt";

        // This will reference one line at a time
        String line = null;

        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = 
                new FileReader(fileName);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = 
                new BufferedReader(fileReader);

            while((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }   

            // Always close files.
            bufferedReader.close();         
        }
        catch(FileNotFoundException ex) {
            System.out.println(
                "Unable to open file '" + 
                fileName + "'");                
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file '" 
                + fileName + "'");                  
            // Or we could just do this: 
            // ex.printStackTrace();
        }
    }
}

【问题讨论】:

  • 你的 test.txt 文件被锁定了吗?要么在其他地方打开编辑?
  • 我猜是找不到文件?
  • 您能否发布异常并在代码中显示它对应的行号。
  • 具体抛出了哪个异常?异常的信息是什么? (提示,ex.getMessage()
  • @Mechkov 它没有被锁定,也没有在其他地方打开。

标签: java hashmap try-catch bufferedreader filereader


【解决方案1】:

尝试将“完整”路径放入文件,而不仅仅是名称。把它写成“用户/.../.../test.txt”。

希望对你有帮助。

【讨论】:

  • 我试过了,但还是无法打开我的文件。
  • 尝试使用 FileInputStream 而不是 FileReader。这是我帮助你的link
猜你喜欢
  • 2013-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2013-04-21
相关资源
最近更新 更多