如何使用相对文件名而不是绝对文件名?

3

我正在让我的程序读取一个 .txt 文件,不想使用绝对文件名,因为它依赖于机器,我只想使用相对文件名。我不知道如何做到这一点。下面是我的程序中涉及到的部分:

private List<String> readFile() {

    List<String> wordsList = new ArrayList<>();

    try {
        String fileName = "C:/Users/Phil/Documents/FourLetterWords.txt";
        File fourLetterWords = new File(fileName);
        Scanner in = new Scanner(fourLetterWords);

        while (in.hasNextLine()) {
            String line = in.nextLine();
            if (line!=null && !line.isEmpty()) {
                wordsList.add(line);
            }
        }
    } 
    catch (FileNotFoundException ex) {
        System.out.println("File not found.");
    }
    return wordsList ;
}

如果我只将其简化为:
"C:/FourLetterWords.txt"

然后我的捕获异常出现并显示“文件未找到”。但我真正想要的是使用...
"FourLetterWords.txt"

4
如果你想做到这一点,那么你必须确保从包含 FourLetterWords.txt 文件的目录中运行程序。此外,你应该考虑将文件名作为参数传递,而不是在程序中硬编码。 - merlin2011
5个回答

3

修改这个

String fileName = "C:/Users/Phil/Documents/FourLetterWords.txt";

转换为类似于

File f = new File(System.getProperty("user.home"),
    "Documents/FourLetterWords.txt");

这将在Java支持的每个平台上获取“user.home”,然后将“Documents/FourLetterWords.txt”附加到该路径。


请注意大小写不敏感的文件系统(FS):返回翻译文本。 - Leo
有没有办法让我做到它可以在不同的操作系统上运行?也许只需使用C:/? - NEPat10
跨操作系统的最佳方法是使用 'System.getProperty("user.dir")' 和/或 'System.getProperty("user.home")'。 - ThisClark
@NEPat10 不同的操作系统不使用 C:/,而这个代码将在 Java 支持的 每个平台 上都能运行。 - Elliott Frisch
好的,因为我的教授会查看这个程序,我希望他能够运行程序并能够访问他系统上的文件。 - NEPat10

1
你可以选择以下方式之一:
  1. 将文件名作为参数传递
  2. 使用 getResourceAsStream() 从与 .class 文件相同的目录加载文件。
  3. System.getProperty("user.dir") 返回当前目录。

1
他们说的没错,此外还有一些有用的技巧可以在文件夹层级之间进行导航:
//absolute path from where application has initialized
String target = System.getProperty("user.dir"); 

//drop the last folder to go down one level
target = target.substring(0, target.lastIndexOf(File.separator)); 

//go into another directory
target = target + File.separator + targetFolder; 

//use it
return target;

0

使用相对文件路径与您当前所在的路径有关。只是猜测,但请尝试 "Documents/FourLetterWords.txt"。

如果这样可以工作,原因是因为您当前的目录是 "C:\Users\Phil"。

如果不行,请尝试

System.out.println("Working Directory = " + System.getProperty("user.dir"));

然后尝试将文件移动到那里以便使用 "FourLetterWords.txt"。


0

Java或任何编程语言中,文件访问有两种情况:

a. 文件存在于项目目录中。
b. 文件不在项目目录中。

a. 文件存在于项目目录中:

文件已经捆绑或推送到项目目录中的文件夹中。在这种情况下,您可以使用类似如下的东西
String fileName = "/resourceFolder/FourLetterWords.txt";

资源文件夹是项目根文件夹的子文件夹。

b. 文件存在于项目目录之外的位置

您需要设置一个属性,该属性将始终具有文件所在的路径。您需要将其设置为环境的一部分,以便代码始终在所有操作系统上运行。您也可以将其设置为属性文件的一部分,该属性文件将针对每个操作系统更改。

获取系统变量:System.getEnv("FILE_DIR");
获取属性:System.getProperty("file.dir");


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接