指定目录时Java.io.FileNotFoundException
我试图用一个名为“helloworld”的txt文件在Java中定义一个文件。我已将此文件放置在资源文件夹中,在创建文件时,我将其定义为:指定目录时Java.io.FileNotFoundException,java,filereader,Java,Filereader,我试图用一个名为“helloworld”的txt文件在Java中定义一个文件。我已将此文件放置在资源文件夹中,在创建文件时,我将其定义为: File file = new File("/helloworld"); 但是,我在编译时遇到了这个错误 Exception in thread "main" java.io.FileNotFoundException: /helloworld (No such file or directory) at java.io.FileInp
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)
谢谢你的帮助
通过转换给定的路径名字符串创建新实例
转换为抽象路径名。如果给定的字符串是空字符串,
然后,结果是空的抽象路径名
您正试图创建一个新的文件
实例,但找不到名为helloworld
的文件,或者是由于其他原因。这就是为什么你会出错
Exception in thread "main" java.io.FileNotFoundException: /helloworld
您说您试图定义一个文件,但您的代码似乎是可读的。如果要创建文件,请尝试下面的一个
诊断起来很容易:您指定的路径以斜杠开始,因此这意味着文件应该位于文件系统的根目录中。最好去掉前导斜杠,然后:
- 或者在文件所在的目录下启动程序
- 实例化
对象时,在代码中指定绝对/相对路径文件
尽管File类对于您尝试执行的操作没有用处,但是您可能需要研究绝对文件名和相对文件名的概念。通过以
/
开头的文件名,您指定了一个绝对文件名,这意味着您告诉程序在一个特定的位置查找该文件,而这个位置几乎肯定不会存在该文件。请尝试下面的方法,以了解您的程序正在查找的文件夹或文件路径在哪里
System.out.println(file.getAbsolutePath());
与
我认为您的程序正在查找c:\helloworld
,并且c
驱动器中没有名为helloword
的文件或文件夹
如果将helloword.txt
放入C
驱动器
File file = new File("C:\\helloworld.txt");
FileNotFoundException
将消失
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();
}
}
}
BufferedReader br = new BufferedReader(
new InputStreamReader(
Tests.class.getResourceAsStream("/helloworld")));
System.out.println(file.getAbsolutePath());
File file = new File("/helloworld");
File file = new File("C:\\helloworld.txt");