简体   繁体   English

指定目录时出现Java.io.FileNotFoundException

[英]Java.io.FileNotFoundException when specifying a directory

I'm trying to define a File in Java with a txt file called "helloworld". 我正在尝试使用名为“ helloworld”的txt文件在Java中定义文件。 I've placed this file in a resources folder and when making the file I defined it like this: 我已将此文件放置在资源文件夹中,并且在制作文件时,我将其定义为:

File file = new File("/helloworld");

However I get this error when compiling 但是我在编译时收到此错误

 Exception in thread "main" java.io.FileNotFoundException: /helloworld 
    (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileReader.<init>(FileReader.java:72)
    at Tests.main(Tests.java:15)

This is the entire code I am trying to execute if that helps troubleshoot this issue 如果可以帮助解决此问题,这是我尝试执行的全部代码

// Java Program to illustrate reading from FileReader
// using BufferedReader
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
public class Tests
{
  public static void main(String[] args)throws Exception
  {


      File file = new File("/helloworld");

      BufferedReader br = new BufferedReader(new FileReader(file));

      String st;
      while ((st = br.readLine()) != null)
        System.out.println(st);
  }
}

Thank you for the help! 感谢您的帮助!

 public File​(String pathname) 

Creates a new File instance by converting the given pathname string into an abstract pathname. 通过将给定的路径名​​字符串转换为抽象路径名来创建新的File实例。 If the given string is the empty string, then the result is the empty abstract pathname. 如果给定的字符串为空字符串,则结果为空的抽象路径名。

You are trying to create a new File instance but the file called helloworld is not found or some other reasons. 您正在尝试创建一个新的File实例,但是找不到名为helloworld的文件或某些其他原因。 That's why you get the error, 这就是为什么你会得到错误,

 Exception in thread "main" java.io.FileNotFoundException: /helloworld
  1. The named file does not exist. 命名文件不存在。
  2. The named file is actually a directory. 命名文件实际上是一个目录。
  3. The named file cannot be opened for reading for some reason. 由于某种原因,无法打开指定文件进行读取。

You say that you try to define a file but your code seems to read. 您说您尝试定义一个文件,但是您的代码似乎可以读取。 Try below one if you want to create a file , 如果要创建文件 ,请尝试以下一种,

import java.io.*;
import java.nio.charset.StandardCharsets;


class TestDir {
    public static void main(String[] args) {
        String fileName = "filename.txt";

        try (Writer writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(fileName), StandardCharsets.UTF_8))) {
            writer.write("write something in text file");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

It is easy to diagnose: The path you specified starts with a slash, so it means that the file is expected to be located at the root directory of the filesystem. 这很容易诊断:您指定的路径以斜杠开头,因此,意味着该文件应位于文件系统的根目录中。 You'd better strip off the leading slash, and: 您最好先去除斜线,然后:

  • Either start your program at the same directory the file is at. 在文件所在的同一目录中启动程序。
  • Either specify an absolute/relative path in your code when instantiating the File object. 实例化File对象时,请在代码中指定绝对/相对路径。

If the file is in a resources folder and is intended to be bundled with your program, you need to treat it like a resource, not a file. 如果该文件位于资源文件夹中并打算与程序捆绑在一起,则需要将其视为资源而不是文件。

This means you should not use the File class. 这意味着您不应使用File类。 You should read your data with the Class.getResource or Class.getResourceAsStream method: 您应该使用Class.getResourceClass.getResourceAsStream方法读取数据:

BufferedReader br = new BufferedReader(
    new InputStreamReader(
        Tests.class.getResourceAsStream("/helloworld")));

This becomes especially important if you want to distribute a program as a .jar file. 如果要将程序作为.jar文件分发,则这一点尤其重要。 A .jar file is a compressed archive (actually a zip file with different extension) which contains both compiled class files and resources. .jar文件是压缩的归档文件(实际上是具有不同扩展名的zip文件),其中包含已编译的类文件和资源。 Since they are all compressed into one .jar file, they are not individual files at all, so there is no way the File class can refer to them. 由于它们都被压缩到一个.jar文件中,因此它们根本不是单独的文件,因此File类无法引用它们。

Although the File class is not useful for what you're trying to do, you may want to research the concept of absolute file names and relative file names. 尽管File类对于您要执行的操作没有用,但是您可能需要研究绝对文件名相对文件名的概念 By starting a file name with / , you are specifying an absolute file name, which means you are telling the program to look for the file in a specific place—a place where the file almost certain will not reside. 通过使用/开头文件名,您可以指定一个绝对文件名,这意味着您要告诉程序在一个特定的位置查找该文件-几乎可以肯定不会驻留该文件的位置。

Try bellow to know where is the folder or file's path, which your program is looking for 尝试下面以了解程序正在寻找的文件夹或文件的路径在哪里

System.out.println(file.getAbsolutePath());

With

File file = new File("/helloworld");

I think your program is looking for c:\\helloworld , and there is no file or folder's name is helloword in your C drive 我认为您的程序正在寻找c:\\helloworld ,并且C盘中没有文件或文件夹的名称是helloword

If you put the helloword.txt into C drive, and 如果将helloword.txt放入C盘,并且

File file = new File("C:\\helloworld.txt");

FileNotFoundException will disappear. FileNotFoundException将消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM