相对文件路径问题 [英] Problem with relative file path

查看:115
本文介绍了相对文件路径问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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")));

我收到错误:

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

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

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

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

我该如何解决?

推荐答案

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

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

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

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".

这篇关于相对文件路径问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆