Java 使用引用路径时FileNotFoundException

Java 使用引用路径时FileNotFoundException,java,file,exception,filenotfoundexception,Java,File,Exception,Filenotfoundexception,我的项目有两个文件夹:folder1和folder2。 在folder1中,我试图使用folder2的引用路径加载folder2中的文件,但它给了我以下异常:java.io.FileNotFoundException:/folder2/blah.txt(没有这样的文件或目录)。当我使用绝对路径时,它工作 file = new FileInputStream("/folder2/blah.txt") 您应该始终通过调用应用程序的根路径来调用路径。我假设folder1和folder2不相关,也就是

我的项目有两个文件夹:
folder1
folder2
。 在
folder1
中,我试图使用folder2的引用路径加载folder2中的文件,但它给了我以下异常:
java.io.FileNotFoundException:/folder2/blah.txt(没有这样的文件或目录)
。当我使用绝对路径时,它工作

file = new FileInputStream("/folder2/blah.txt")

您应该始终通过调用应用程序的根路径来调用路径。我假设folder1和folder2不相关,也就是说,folder2不在folder1中,这就是它发生的原因

请检查以获取根路径,然后您可以随意访问目录

通过其他方式,您可以尝试:

String path = new File(".").getCanonicalPath();
file = new FileInputStream( path + "/folder2/blah.txt"); // I have not tested here. If it returns an error try removing the / from the beginning of the folder2

这是一个非常简单的解决方案。您正试图在系统中的/folder2/blah.properties加载该文件。但是,如果它只是在Java项目的类路径中,则省略初始文件路径分隔符

试着这样做:

//Initial seperator is oitted.
file = new FileInputStream("folder2/blah.txt")

folder1和folder2是否具有相同的父级?@helpYou是,返回它们的doSame异常