使用 IntelliJ IDEA 在 Java 中引用具有相对路径的文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30765270/
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
Reference a Text File with relative path in Java with the IntelliJ IDEA
提问by gangwerz
I have a program that reads numbers from a .txt
file. My problem is where to place this file, or how to reference it with a relative path to make this file accessible without using the absolute path.
我有一个从.txt
文件中读取数字的程序。我的问题是将这个文件放在哪里,或者如何使用相对路径引用它以在不使用绝对路径的情况下访问该文件。
回答by Fran
When you try to open a file, it takes your current working path. For example this working tree:
当您尝试打开文件时,它会使用您当前的工作路径。例如这个工作树:
Project
|->src
| |-->MyClass.java
| |-->MyFile1.txt
|->res
|->files
|-->MyFile2.txt
You can use
您可以使用
new File("MyFile1.txt");
new File("MyFile1.txt");
for MyFile1, or
对于 MyFile1,或
new File("./res/files/MyFile2.txt");
new File("./res/files/MyFile2.txt");
for MyFile2.
对于 MyFile2。