Java new File() 说 FileNotFoundException 但文件存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19307622/
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 15:55:33  来源:igfitidea点击:

Java new File() says FileNotFoundException but file exists

javafilenotfoundexception

提问by scrblnrd3

I have an assignment for my CS class where it says to read a file with several test scores and asks me to sum and average them. While summing and averaging is easy, I am having problems with the file reading. The instructor said to use this syntax

我的 CS 课有一个作业,它说要阅读一个包含多个测试分数的文件,并要求我对它们求和并求平均值。虽然求和和求平均很容易,但我在读取文件时遇到了问题。老师说要用这个语法

Scanner scores=new Scanner(new File("scores.dat"));

However, this throws a FileNotFoundException, but I have checked over and over again to see if the file exists in the current folder, and after that, I figured that it had to do something with the permissions. I changed the permissions for read and write for everyone, but it still did not work and it still keeps throwing the error. Does anyone have any idea why this may be occurring?

但是,这会引发 FileNotFoundException,但我一遍又一遍地检查当前文件夹中是否存在该文件,然后我认为它必须对权限执行某些操作。我更改了每个人的读写权限,但它仍然不起作用,并且仍然不断抛出错误。有谁知道为什么会发生这种情况?

EDIT: It was actually pointing to a directory up, however, I have fixed that problem. file.exists() returns true, however, when I try to put it in the scanner, it throws the filenotfoundexception

编辑:它实际上是指向一个目录,但是,我已经解决了这个问题。file.exists() 返回true,但是,当我尝试将其放入扫描仪时,它会抛出 filenotfoundexception

Here is all my code

这是我所有的代码

import java.util.Scanner;
import java.io.*;
public class readInt{
        public static void main(String args[]){
                File file=new File("lines.txt");
                System.out.println(file.exists());
                Scanner scan=new Scanner(file);
        }
}

采纳答案by Terry Li

There are a number situation where a FileNotFoundExceptionmay be thrown at runtime.

在很多情况下, aFileNotFoundException可能会在运行时抛出。

  1. The named file does not exist. This could be for a number of reasons including:

    • The pathname is simply wrong
    • The pathname looks correct but is actually wrong because it contains non-printing characters (or homoglyphs) that you did not notice
    • The pathname is relative, and it doesn't resolve correctly relative to the actualcurrent directory of the running application. This typically happens because the application's current directory is not what you are expecting or assuming.
    • The path to the file is is broken; e.g. a directory name of the path is incorrect, a symbolic link on the path is broken, or there is a permission problem with one of the path components.
  2. The named file is actually a directory.

  3. The named file cannot be opened for reading for some reason.
  1. 命名的文件不存在。这可能有多种原因,包括:

    • 路径名完全错误
    • 路径名看起来正确但实际上是错误的,因为它包含您没有注意到的非打印字符(或同形文字)
    • 路径名是相对的,相对于正在运行的应用程序的实际当前目录,它不能正确解析。这通常是因为应用程序的当前目录不是您所期望或假设的。
    • 文件路径损坏;例如,路径的目录名称不正确,路径上的符号链接已损坏,或者路径组件之一存在权限问题。
  2. 命名文件实际上是一个目录。

  3. 由于某种原因,无法打开命名文件进行读取。

The good news that, the problem will inevitablybe one of the above. It is just a matter of working out which. Here are some things that you can try:

好消息是,问题必然是上述问题之一。这只是一个解决问题的问题。以下是您可以尝试的一些事情:

  • Calling file.exists()will tell you if any file system object exists with the given name / pathname.
  • Calling file.isDirectory()will test if it is a directory.
  • Calling file.canRead()will test if it is a readable file.
  • This line will tell you what the current directory is:

    System.out.println(new File(".").getAbsolutePath());
    
  • This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trainiong whitespace:

    System.out.println("The path is '" + path + "'");
    

    Look for unexpected spaces, line breaks, etc in the output.

  • 调用file.exists()将告诉您是否存在具有给定名称/路径名的任何文件系统对象。
  • 调用file.isDirectory()将测试它是否是目录。
  • 调用file.canRead()将测试它是否是可读文件。
  • 这一行会告诉你当前目录是什么:

    System.out.println(new File(".").getAbsolutePath());
    
  • 这一行将以一种更容易发现意外前导或训练空格之类的方式打印出路径名:

    System.out.println("The path is '" + path + "'");
    

    在输出中查找意外的空格、换行符等。



It turns out that your example code has a compilation error.

事实证明,您的示例代码存在编译错误。

I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:

我在没有处理 Netbeans 投诉的情况下运行了您的代码,结果却收到了以下异常消息:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

线程“main”中的异常 java.lang.RuntimeException: 无法编译的源代码 - 未报告的异常 java.io.FileNotFoundException; 必须被捕获或声明被抛出

If you change your code to the following, it will fix thatproblem.

如果您将代码更改为以下内容,它将解决问题。

public static void main(String[] args) throws FileNotFoundException {    
    File file = new File("scores.dat");
    System.out.println(file.exists());
    Scanner scan = new Scanner(file);
}

Explanation: the Scanner(File)constructor is declared as throwing the FileNotFoundExceptionexception. (It happens the scanner it cannot open the file.) Now FileNotFoundExceptionis a checked exception. That means that a method in which the exception may bethrown musteither catch the exception or declare it in the throwsclause. The above fix takes the latter approach.

说明Scanner(File)构造函数被声明为抛出FileNotFoundException异常。(它碰巧扫描仪无法打开文件。)现在FileNotFoundException是一个已检查的异常。这意味着可能抛出异常的方法必须捕获异常或在throws子句中声明它。上述修复采用后一种方法。

回答by libik

The code itself is working correctly. The problem is, that the program working path is pointing to other place than you think.

代码本身工作正常。问题是,程序工作路径指向的地方比你想象的要多。

Use this line and see where the path is:

使用此行并查看路径在哪里:

System.out.println(new File(".").getAbsoluteFile());

回答by petehern

Obviously there are a number of possible causes and the previous answers document them well, but here's how I solved this for in one particular case:

显然有许多可能的原因,之前的答案很好地记录了它们,但这是我在一个特定情况下解决这个问题的方法:

A student of mine had this problem and I nearly tore my hair out trying to figure it out. It turned out that the file didn't exist, even though it looked like it did. The problem was that Windows 7 was configured to "Hide file extensions for known file types." This means that if file appears to have the name "data.txt" its actualfilename is "data.txt.txt".

我的一个学生遇到了这个问题,我差点把头发扯掉试图弄清楚。结果发现该文件不存在,即使它看起来确实存在。问题在于 Windows 7 被配置为“隐藏已知文件类型的文件扩展名”。这意味着如果文件似乎具有名称“data.txt”,则其实际文件名是“data.txt.txt”。

Hope this helps others save themselves some hair.

希望这可以帮助其他人节省一些头发。

回答by yurin

I recently found interesting case that produces FileNotFoundExeption when file is obviously exists on the disk. In my program I read file path from another text file and create File object:

我最近发现了一个有趣的案例,当文件明显存在于磁盘上时,它会产生 FileNotFoundExeption。在我的程序中,我从另一个文本文件中读取文件路径并创建 File 对象:

//String path was read from file
System.out.println(path); //file with exactly same visible path exists on disk
File file = new File(path); 
System.out.println(file.exists());  //false
System.out.println(file.canRead());  //false
FileInputStream fis = new FileInputStream(file);  // FileNotFoundExeption 

The cause of the problem was that the path contained invisible \r\ncharacters at the end.

问题的原因是路径\r\n末尾包含不可见字符。

The fix in my case was:

在我的情况下的修复是:

File file = new File(path.trim()); 

To generalize a bit, the invisible / non-printing characters could have include space or tab characters, and possibly others, and they could have appeared at the beginning of the path, at the end, or embedded in the path. Trim will work in some cases but not all. There are a couple of things that you can help to spot this kind of problem:

概括地说,不可见/非打印字符可能包含空格或制表符,也可能包含其他字符,它们可能出现在路径的开头、结尾或嵌入路径中。Trim 在某些情况下会起作用,但不是全部。有几件事可以帮助您发现此类问题:

  1. Output the pathname with quote characters around it; e.g.

      System.out.println("Check me! '" + path + "'");
    

    and carefully check the output for spaces and line breaks where they shouldn't be.

  2. Use a Java debugger to carefully examine the pathname string, character by character, looking for characters that shouldn't be there. (Also check for homoglyph characters!)

  1. 输出带有引号字符的路径名;例如

      System.out.println("Check me! '" + path + "'");
    

    并仔细检查输出中不应该出现的空格和换行符。

  2. 使用 Java 调试器逐个字符地仔细检查路径名字符串,查找不应该存在的字符。(还要检查同形文字字符!)

回答by Alok

Apart from all the other answers mentioned here, you can do one thing which worked for me.

除了这里提到的所有其他答案之外,您还可以做一件对我有用的事情。

If you are reading the path through Scanner or through command line args, instead of copy pasting the path directly from Windows Explorer just manually type in the path.

如果您通过 Scanner 或命令行参数读取路径,则无需直接从 Windows 资源管理器中复制粘贴路径,只需手动输入路径即可。

It worked for me, hope it helps someone :)

它对我有用,希望它可以帮助某人:)

回答by Solumyr

Reading and writing from and to a file can be blocked by your OS depending on the file's permission attributes.

根据文件的权限属性,您的操作系统可以阻止读取和写入文件。

If you are trying to read from the file, then I recommend using File's setReadable method to set it to true, or, this code for instance:

如果您尝试从文件中读取,那么我建议使用 File 的 setReadable 方法将其设置为 true,或者,例如以下代码:

String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file;
File f = new File(arbitrary_path);
f.setReadable(true);
data_of_file = Files.readAllBytes(f);
f.setReadable(false); // do this if you want to prevent un-knowledgeable 
                      //programmers from accessing your file.

If you are trying to write to the file, then I recommend using File's setWritable method to set it to true, or, this code for instance:

如果您正在尝试写入文件,那么我建议使用 File 的 setWritable 方法将其设置为 true,或者,例如以下代码:

String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file = { (byte) 0x00, (byte) 0xFF, (byte) 0xEE };
File f = new File(arbitrary_path);
f.setWritable(true);
Files.write(f, byte_array);
f.setWritable(false); // do this if you want to prevent un-knowledgeable 
                      //programmers from changing your file (for security.)

回答by Irina Larisa

An easy fix, which worked for me, is moving my files out of src and into the main folder of the project. It's not the best solution, but depending on the magnitude of the project and your time, it might be just perfect.

一个对我有用的简单修复方法是将我的文件从 src 移到项目的主文件夹中。这不是最好的解决方案,但根据项目的规模和您的时间,它可能是完美的。

回答by lewiscool

I had this same error and solved it simply by adding the src directory that is found in Java project structure.

我遇到了同样的错误,只需添加在 Java 项目结构中找到的 src 目录即可解决。

String path = System.getProperty("user.dir") + "\src\package_name\file_name";
File file = new File(path);
Scanner scanner = new Scanner(file);

Notice that System.getProperty("user.dir") and new File(".").getAbsolutePath() return your project root directory path, so you have to add the path to your subdirectories and packages

请注意 System.getProperty("user.dir") 和 new File(".").getAbsolutePath() 返回您的项目根目录路径,因此您必须将路径添加到您的子目录和包

回答by Aditya Vikas Devarapalli

You'd obviously figure it out after a while but just posting this so that it might help someone. This could also happen when your file path contains any whitespace appended or prepended to it.

你显然会在一段时间后弄清楚,但只是发布这个以便它可以帮助某人。当您的文件路径包含任何附加或前置的空格时,也可能发生这种情况。

回答by Lefin K.R

Use single forward slash and always type the path manually. For example:

使用单个正斜杠并始终手动键入路径。例如:

FileInputStream fi= new FileInputStream("D:/excelfiles/myxcel.xlsx");