Java IO给了我一个错误

时间:2011-08-13 18:22:12

标签: java java-io

当我运行以下代码时,出现错误。

package practicing.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class JavaIO {
  public static void main(String[] args) throws IOException {
    FileInputStream in = null;
    FileOutputStream out = null;
    try {
        in = new FileInputStream("xanaduout.txt");
        out = new FileOutputStream("out.txt");
        int c;

        while ((c = in.read()) != -1) {
            out.write(c);
        }

    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
   }
}

这是从Sun的在线教程中获得的。请告诉我出了什么问题。

3 个答案:

答案 0 :(得分:1)

提供文件的确切位置。

你应该试试

   in = new FileInputStream("c:\xanaduout.txt");

而不是这个

   in = new FileInputStream("xanaduout.txt");

答案 1 :(得分:1)

“xanaduout.txt”是否存在?在您当前的目录中?

如果没有,您可以随时对路径进行硬编码。但这不是好的做法:)

在任何情况下,错误都说明发生了什么:您正在尝试打开文件......系统无法找到它。

答案 2 :(得分:1)

错误消息显示:

Exception in thread "main" java.io.FileNotFoundException: xanaduout.txt 
(The system cannot find the file specified)

似乎源自代码的第12行:

at practicing.io.JavaIO.main(JavaIO.java:12)

代码的第12行是:

in = new FileInputStream("xanaduout.txt");

所以你试图从文件xanaduout.txt中读取而Java正在抱怨它无法找到该文件。

修改

@Keith Mattix编辑您的程序以打印出它正在读取的文件的路径,并确认该文件确实存在于磁盘上:

public class JavaIO {
  public static void main(String[] args) throws IOException {
    FileInputStream in = null;
    FileOutputStream out = null;
    try {
        File file = new File("xanaduout.txt");
        System.out.println("My program is going to read the file " +
            file.getCanonicalPath() + " which " + (file.exists()? "" : "does not") +
            " exist on disk"); 
        in = new FileInputStream(file);
        out = new FileOutputStream("out.txt");
        int c;

        while ((c = in.read()) != -1) {
            out.write(c);
        }

    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
   }
}