首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java IO给我一个错误

Java IO给我一个错误
EN

Stack Overflow用户
提问于 2011-08-14 02:22:12
回答 3查看 860关注 0票数 0

当我运行下面的代码时,我得到一个错误。

代码语言:javascript
复制
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的在线教程中摘录的。请告诉我出什么事了。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-08-14 02:30:10

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

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

在任何情况下,该错误都会准确地说明所发生的情况:您正在尝试打开一个文件...系统找不到它。

票数 1
EN

Stack Overflow用户

发布于 2011-08-14 02:29:10

给出文件的确切位置。

你应该试试

代码语言:javascript
复制
   in = new FileInputStream("c:\xanaduout.txt");

而不是这个

代码语言:javascript
复制
   in = new FileInputStream("xanaduout.txt");
票数 1
EN

Stack Overflow用户

发布于 2011-08-14 02:31:03

错误消息显示:

代码语言:javascript
复制
Exception in thread "main" java.io.FileNotFoundException: xanaduout.txt 
(The system cannot find the file specified)

并且似乎源自您代码的第12行:

代码语言:javascript
复制
at practicing.io.JavaIO.main(JavaIO.java:12)

代码的第12行是:

代码语言:javascript
复制
in = new FileInputStream("xanaduout.txt");

因此,您正在尝试从文件xanaduout.txt读取,而Java抱怨它找不到该文件。

编辑

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

代码语言:javascript
复制
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();
        }
    }
   }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7052416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档