【问题标题】:Cannot Create normal File.txt with Eclipse无法使用 Eclipse 创建普通 File.txt
【发布时间】:2014-11-13 22:26:45
【问题描述】:

我有一个问题,我无法创建一个正常的文件! 这是我的代码:

public class test {

    public static void main(String[] args) throws Exception {
        File myFile = new File("word.txt");
        System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());

        Scanner input = new Scanner(myFile);
        String in = "";
        in = input.nextLine();
    }

}

我有这个错误:

Attempting to read from file in: C:\Users\AHMED\workspace\Video\word.txt
Exception in thread "main" java.io.FileNotFoundException: word.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.util.Scanner.<init>(Unknown Source)
    at test.main(test.java:11)

【问题讨论】:

  • ...那个文件存在吗?
  • 这个错误有什么难以理解的地方?您正在尝试从一个不存在的文件中读取,那么除了异常之外您还期望什么?
  • 好吧,我想这不是通过尝试读取文件来创建文件的“正常”方式。搜索有关使用 Java 创建文件的千篇一律的教程。
  • 我很好奇他创建了文件并且他想从同一个文件中读取。为什么没有创建文件?
  • 我真的不知道!我正在使用 Sphinx 项目,但我注意到它无法读取任何目录......所以我只创建一个新文件来测试它,但它不起作用......

标签: java eclipse


【解决方案1】:

这一行:

File myFile = new File("word.txt");

不在磁盘上创建新文件。它只是在内存中创建一个 File 对象。

因此,当您尝试从文件中读取时,它不存在(在磁盘上),因此您的错误。

要真正在磁盘上创建一个真实的文件,你需要向它写入数据,或者通过“触摸”文件来创建一个空文件:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多