【问题标题】:Java File I/O: Why do I always get an I/O exception?Java 文件 I/O:为什么总是出现 I/O 异常?
【发布时间】:2015-01-17 15:54:19
【问题描述】:

我正在尝试写入文件,然后从同一个文件中读取。输出为“错误:I/O 异常”。这意味着程序正在捕获 IOException。

public class fileIO {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try
        {
            File file = new File("io.txt");
            BufferedReader read = new BufferedReader(new FileReader(file));
            BufferedWriter write = new BufferedWriter(new FileWriter(file));

            String needs = "This is going to the file";
            write.write(needs);

            String  stuff = read.readLine();
            while(stuff != null)
            {
                System.out.println(stuff);
                stuff = read.readLine();
            }

        }
        catch(IOException e)
        {
            System.out.println("Error: I/O Exception");
        }
        catch(NullPointerException e)
        {
            System.out.println("Error: NullPointerException");
        }
    }
}'

【问题讨论】:

  • 你得到什么异常? FileNotFound?
  • 查看堆栈跟踪,您应该将其添加到问题中。可以通过在 catch 块中执行 e.printStackTrace() 来简单地完成。
  • 打印堆栈跟踪会告诉你更多关于哪里出了问题。让main 抛出异常而不是捕获它。
  • 我的猜测是他在同一时间写入和读取同一个文件。

标签: java file-io bufferedreader ioexception bufferedwriter


【解决方案1】:

您不能同时读取和写入文件,这将引发IOException。在尝试用其他东西访问它之前,您应该关闭任何可以访问该文件的东西。在尝试使用BufferedReader 访问文件之前,在BufferedWriter 上调用close() 方法应该可以解决问题。

编辑:另外,正如其他人所提到的,您可以使用e.printStackTrace() 查看程序中发生异常的位置,这对调试有很大帮助。

编辑: 正如 zapl 所阐明的,这适用于某些文件系统,包括 Windows,但并非全部。我假设您使用的文件系统限制了这一点,因为这似乎是最有可能出现的问题。

【讨论】:

  • @zapl 谢谢你,我已经修改了我的答案。
【解决方案2】:

我将 BufferedReader 移到了我关闭 BufferedWriter 的位置之后,就成功了。感谢您的帮助。

公共类文件IO {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try
    {
        File file = new File("io.txt");
        BufferedWriter write = new BufferedWriter(new FileWriter(file));

        String needs = "This is going to the file";
        write.write(needs);
        write.close();

        BufferedReader read = new BufferedReader(new FileReader(file));

        String  stuff = read.readLine();
        while(stuff != null)
        {
            System.out.println(stuff);
            stuff = read.readLine();
        }
        read.close();
    }
    catch(IOException e)
    {
        System.out.println("Error: I/O Exception");
        e.printStackTrace();
    }
    catch(NullPointerException e)
    {
        System.out.println("Error: NullPointerException");
        e.printStackTrace();
    }
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 2014-04-05
    • 2012-11-25
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    相关资源
    最近更新 更多