繁体   English   中英

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

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

我正在尝试使用名为“ helloworld”的txt文件在Java中定义文件。 我已将此文件放置在资源文件夹中,并且在制作文件时,我将其定义为:

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

但是我在编译时收到此错误

 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)

如果可以帮助解决此问题,这是我尝试执行的全部代码

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

感谢您的帮助!

 public File​(String pathname) 

通过将给定的路径名​​字符串转换为抽象路径名来创建新的File实例。 如果给定的字符串为空字符串,则结果为空的抽象路径名。

您正在尝试创建一个新的File实例,但是找不到名为helloworld的文件或某些其他原因。 这就是为什么你会得到错误,

 Exception in thread "main" java.io.FileNotFoundException: /helloworld
  1. 命名文件不存在。
  2. 命名文件实际上是一个目录。
  3. 由于某种原因,无法打开指定文件进行读取。

您说您尝试定义一个文件,但是您的代码似乎可以读取。 如果要创建文件 ,请尝试以下一种,

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

这很容易诊断:您指定的路径以斜杠开头,因此,意味着该文件应位于文件系统的根目录中。 您最好先去除斜线,然后:

  • 在文件所在的同一目录中启动程序。
  • 实例化File对象时,请在代码中指定绝对/相对路径。

如果该文件位于资源文件夹中并打算与程序捆绑在一起,则需要将其视为资源而不是文件。

这意味着您不应使用File类。 您应该使用Class.getResourceClass.getResourceAsStream方法读取数据:

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

如果要将程序作为.jar文件分发,则这一点尤其重要。 .jar文件是压缩的归档文件(实际上是具有不同扩展名的zip文件),其中包含已编译的类文件和资源。 由于它们都被压缩到一个.jar文件中,因此它们根本不是单独的文件,因此File类无法引用它们。

尽管File类对于您要执行的操作没有用,但是您可能需要研究绝对文件名相对文件名的概念 通过使用/开头文件名,您可以指定一个绝对文件名,这意味着您要告诉程序在一个特定的位置查找该文件-几乎可以肯定不会驻留该文件的位置。

尝试下面以了解程序正在寻找的文件夹或文件的路径在哪里

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

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

我认为您的程序正在寻找c:\\helloworld ,并且C盘中没有文件或文件夹的名称是helloword

如果将helloword.txt放入C盘,并且

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

FileNotFoundException将消失。

暂无
暂无

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

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