java.io.FileNotFoundException: 系统找不到指定的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19871955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:56:13  来源:igfitidea点击:

java.io.FileNotFoundException: the system cannot find the file specified

javafile-iofilenotfoundexception

提问by name123

I have a file named "word.txt".

我有一个名为“ word.txt”的文件。

It is in the same directory as my javafile.

它与我的java文件在同一目录中。

But when I try to access it in the following code this file not founderror occurs:

但是,当我尝试在以下代码中访问它时,会发生此文件未找到错误:

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 Hangman1.main(Hangman1.java:6)

Here's my code:

这是我的代码:

import java.io.File;
import java.util.*;

public class Hangman1 {
    public static void main(String[] args) throws Exception {
        Scanner input = new Scanner(new File("word.txt"));          
        String in = "";         
        in = input.nextLine();          
    }
}

采纳答案by Paul Samsotha

Put the word.txt directly as a child of the project root folder and a peer of src

直接把word.txt作为项目根文件夹的子目录和src的peer

Project_Root
    src
    word.txt

Disclaimer:I'd like to explain why this works for this particular case and why it may not work for others.

免责声明:我想解释为什么这适用于这个特殊情况以及为什么它可能不适用于其他人。

Why it works:

为什么有效:

When you use Fileor any of the other FileXxxvariants, you are looking for a file on the file system relative to the "working directory". The working directory, can be described as this:

当您使用File或任何其他FileXxx变体时,您正在文件系统上寻找相对于“工作目录”的文件。工作目录,可以这样描述:

When you run from the command line

从命令行运行时

C:\EclipseWorkspace\ProjectRoot\bin > java com.mypackage.Hangman1

C:\EclipseWorkspace\ProjectRoot\bin > java com.mypackage.Hangman1

the working directory is C:\EclipseWorkspace\ProjectRoot\bin. With your IDE (at least all the ones I've worked with), the working directory is the ProjectRoot. So when the file is in the ProjectRoot, then using just the file name as the relative path is valid, because it is at the root of the working directory.

工作目录是C:\EclipseWorkspace\ProjectRoot\bin. 对于您的 IDE(至少是我使用过的所有 IDE),工作目录是ProjectRoot. 因此,当文件位于 中时ProjectRoot,仅使用文件名作为相对路径是有效的,因为它位于工作目录的根目录中。

Similarly, if this was your project structure ProjectRoot\src\word.txt, then the path "src/word.txt"would be valid.

同样,如果这是您的项目结构ProjectRoot\src\word.txt,那么路径"src/word.txt"将是有效的。

Why it May not Work

为什么它可能不起作用

For one, the working directory could always change. For instance, running the code from the command line like in the example above, the working directory is the bin. So in this case it will fail, as there is not bin\word.txt

一方面,工作目录总是会改变。例如,像上面的例子一样从命令行运行代码,工作目录是bin. 所以在这种情况下它会失败,因为没有bin\word.txt

Secondly, if you were to export this project into a jar, and the file was configured to be included in the jar, it would also fail, as the path will no longer be valid either.

其次,如果您要将这个项目导出到 jar 中,并且该文件被配置为包含在 jar 中,它也会失败,因为路径也不再有效。

That being said, you need to determine if the file is to be an embedded-resource(or just "resource" - terms which sometimes I'll use interchangeably). If so, then you will want to build the file into the classpath, and access it via an URL. First thing you would need to do (in this particular) case is make sure that the file get builtinto the classpath. With the file in the project root, you must configure the build to include the file. Butif you put the file in the srcor in some directory below, then the default build should put it into the class path.

话虽如此,您需要确定文件是否是嵌入式资源(或只是“资源”——有时我会互换使用的术语)。如果是这样,那么您需要将文件构建到类路径中,并通过 URL 访问它。您需要做的第一件事(在这种特殊情况下)是确保将文件内置到类路径中。使用项目根目录中的文件,您必须配置构建以包含该文件。但是如果你把文件放在src下面的某个目录中,那么默认构建应该把它放到类路径中。

You can access classpath resource in a number of ways. You can make use of the Classclass, which has getResourceXxxmethod, from which you use to obtain classpath resources.

您可以通过多种方式访问​​类路径资源。您可以使用Class具有getResourceXxx方法的类,您可以从中获取类路径资源。

For example, if you changed your project structure to ProjectRoot\src\resources\word.txt, you could use this:

例如,如果您将项目结构更改为ProjectRoot\src\resources\word.txt,则可以使用:

InputStream is = Hangman1.class.getResourceAsStream("/resources/word.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));

getResourceAsStreamreturns an InputStream, but obtains an URL under the hood. Alternatively, you could get an URLif that's what you need. getResource()will return an URL

getResourceAsStream返回一个InputStream,但在引擎盖下获取一个 URL。或者,URL如果这就是您所需要的,您可以获得一个。getResource()将返回一个 URL

For Maven users, where the directory structure is like src/main/resources, the contents of the resourcesfolder is put at the root of the classpath. So if you have a file in there, then you would only use getResourceAsStream("/thefile.txt")

对于 Maven 用户,目录结构类似于src/main/resourcesresources文件夹的内容放在类路径的根目录下。所以如果你有一个文件,那么你只会使用getResourceAsStream("/thefile.txt")

回答by acdcjunior

Relative paths can be used, but they can be tricky. The best solution is to know where your files are being saved, that is, print the folder:

可以使用相对路径,但它们可能很棘手。最好的解决方案是知道您的文件保存在哪里,即打印文件夹:

import java.io.File;
import java.util.*;

public class Hangman1 {

    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();
    }

}

This code should print the folder where it is looking for. Place the file there and you'll be good to go.

此代码应打印要查找的文件夹。将文件放在那里,您就可以开始使用了。

回答by LotusUNSW

Your file should directly be under the project folder, and not inside any other sub-folder.

您的文件应该直接在项目文件夹下,而不是在任何其他子文件夹中。

If the folder of your project is named for e.g. AProject, it should be in the same place as your srcfolder.

如果您的项目文件夹以 eg 命名AProject,则它应该与您的src文件夹位于同一位置。

Aproject
        src
        word.txt

回答by Алексей

i think it always boils to the classpath. having said that if you run from the same folder where your .class is then change Scanner input = new Scanner(new File("word.txt"));to Scanner input = new Scanner(new File("./word.txt"));that should work

我认为它总是沸腾到classpath. 话说回来,如果你从那里您的.class是同一个文件夹,然后运行的变化Scanner input = new Scanner(new File("word.txt"));,以Scanner input = new Scanner(new File("./word.txt"));应工作

回答by Victor

Make sure when you create a txt file you don't type in the name "name.txt", just type in "name". If you type "name.txt" Eclipse will see it as "name.txt.txt". This solved it for me. Also save the file in the src folder, not the folder were the .java resides, one folder up.

确保在创建 txt 文件时不要输入名称“name.txt”,只需输入“name”。如果您键入“name.txt”,Eclipse 会将其视为“name.txt.txt”。这为我解决了它。还将文件保存在 src 文件夹中,而不是 .java 所在的文件夹,一个文件夹。

回答by Neftanic

I was reading path from a properties file and didn't mention there was a space in the end. Make sure you don't have one.

我正在从属性文件中读取路径,并没有提到最后有一个空格。确保你没有。

回答by Miner Dev

I have the same problem, but you know why? because I didn't put .txt in the end of my File and so it was File not a textFile, you shoud do just two things:

我有同样的问题,但你知道为什么吗?因为我没有把 .txt 放在我的文件的末尾,所以它是文件而不是文本文件,你应该只做两件事:

  1. Put your Text File in the Root Directory (e.x if you have a project called HelloWorld, just right-click on the HelloWorld file in the package Directory and create File
  2. Save as that File with any name that you want but with a .txt in the end of that I guess your problem is solved, but I write it to other peoples know that. Thanks.
  1. 将您的文本文件放在根目录中(例如,如果您有一个名为 HelloWorld 的项目,只需右键单击包目录中的 HelloWorld 文件并创建 File
  2. 使用您想要的任何名称另存为该文件,但最后使用 .txt 我想您的问题已解决,但我将其写给其他人知道这一点。谢谢。

回答by Promod Kumar

Try to create a file using the code, so you will get to know the path of the file where the system create

尝试使用代码创建一个文件,这样你就会知道系统创建的文件的路径

File test=new File("check.txt");
if (test.createNewFile()) {
    System.out.println("File created: " + test.getName());
  }