Java 相对文件路径问题

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

Problem with relative file path

javaeclipse

提问by Richard Knop

So here is my program, which works ok:

所以这是我的程序,它可以正常工作:

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Locale;

public class ScanSum {
    public static void main(String[] args) throws IOException {
        Scanner s = null;
        double sum = 0;
        try {
            s = new Scanner(new BufferedReader(new FileReader("D:/java-projects/HelloWorld/bin/usnumbers.txt")));
            s.useLocale(Locale.US);

            while (s.hasNext()) {
                if (s.hasNextDouble()) {
                    sum += s.nextDouble();
                } else {
                    s.next();
                }
            }
        } finally {
            s.close();
        }

        System.out.println(sum);
    }
}

As you can see, I am using absolute path to the file I am reading from:

如您所见,我使用的是我正在读取的文件的绝对路径:

s = new Scanner(new BufferedReader(new FileReader("D:/java-projects/HelloWorld/bin/usnumbers.txt")));

The problem arises when I try to use the relative path:

当我尝试使用相对路径时出现问题:

s = new Scanner(new BufferedReader(new FileReader("usnumbers.txt")));

I get an error:

我收到一个错误:

Exception in thread "main" java.lang.NullPointerException
    at ScanSum.main(ScanSum.java:24)

The file usnumbers.txt is in the same directory as the ScanSum.class file:

文件 usnumbers.txt 与 ScanSum.class 文件位于同一目录中:

D:/java-projects/HelloWorld/bin/ScanSum.class
D:/java-projects/HelloWorld/bin/usnumbers.txt

How could I solve this?

我怎么能解决这个问题?

采纳答案by aioobe

From which directory is the class file executed? (That would be the current working directory and base directory for relative paths.)

从哪个目录执行类文件?(这将是相对路径的当前工作目录和基目录。)

If you simply launch the application from eclipse, the project directory will be the working directory, and you should in that case use "bin/usnumbers.txt".

如果您只是从 Eclipse 启动应用程序,项目目录将是工作目录,在这种情况下您应该使用"bin/usnumbers.txt".

回答by erickson

The NullPointerExceptionis due to the fact that new FileReader()expression is throwing a FileNotFoundException, and the variable sis never re-assigned a non-null value.

NullPointerException是由于new FileReader()表达式抛出 a FileNotFoundException,并且变量s永远不会重新分配一个非空值。

The file "usnumbers.txt" is not found because relative paths are resolved (as with all programs) relative to the current working directory, not one of the many entries on the classpath.

找不到文件“usnumbers.txt”,因为相对路径是相对于当前工作目录解析的(与所有程序一样),而不是类路径上的众多条目之一。

To fix the first problem, never assign a meaningless nullvalue just to hush the compiler warnings about unassigned variables. Use a pattern like this:

要解决第一个问题,永远不要分配一个无意义的null值只是为了让编译器对未分配的变量发出警告。使用这样的模式:

FileReader r = new FileReader(path);
try {
  Scanner s = new Scanner(new BufferedReader(r));
  ...
} finally {
  r.close();
}

For the second problem, change directories to the directory that contains "usnumbers.txt" before launching java. Or, move that file to the directory from which javais run.

对于第二个问题,在启动之前将目录更改为包含“usnumbers.txt”的目录java。或者,将该文件移动到java运行的目录。

回答by oks16

It must be a FileNotFoundException causing NPE in the finally block. Eclipse, by default, executes the class with the project folder (D:/java-projects/HelloWorldin your case ) as the working directory. Put the usnumbers.txt file in that folder and try. Or change the working directory in Run Configuration -> Argument tab

它必须是 FileNotFoundException 导致 finally 块中的 NPE。默认情况下,Eclipse 使用项目文件夹(在您的情况下为D:/java-projects/HelloWorld)作为工作目录执行类。将 usnumbers.txt 文件放在该文件夹中并尝试。或者在 Run Configuration -> Argument 选项卡中更改工作目录

回答by pdbartlett

If aioobe@'s suggestion doesn't work for you, and you need to find out which directory the app is running from, try logging the following:

如果 aioobe@ 的建议对您不起作用,并且您需要找出应用程序从哪个目录运行,请尝试记录以下内容:

new File(".").getAbsolutePath()

回答by theSaan

In Eclipse, you can also look under "Run Configurations->Than TAB "Classpath".

在 Eclipse 中,您还可以在“Run Configurations->Than TAB”Classpath”下查看。

By default the absolut path is listed under "User Entries" in [icon] 'your.path' (default classpath)

默认情况下,绝对路径列在 [ icon] ' your.path' (默认类路径)中的“用户条目”

回答by jiming

Since your working directory is “D:/java-projects/HelloWorld”

由于您的工作目录是“D:/java-projects/HelloWorld”

@pdbartlett's id is great, But String filePath = new File(".").getAbsolutePath()will output "D:/java-projects/HelloWorld/." which is not easy to add your extra relative path like "filePath" + "/src/main/resources/" + FILENAME which located in resources folder.

@pdbartlett 的 id 很棒,但 String filePath = new File(".").getAbsolutePath()会输出“D:/java-projects/HelloWorld/”。添加额外的相对路径并不容易,例如位于资源文件夹中的“filePath”+“/src/main/resources/”+ FILENAME。

I suggest with String filePath = new File("").getAbsolutePath()which return the project root folder

我建议用String filePath = new File("").getAbsolutePath()which 返回项目根文件夹