[英]Reference a Text File with relative path in Java with the IntelliJ IDEA
I have a program that reads numbers from a .txt
file.我有一个从
.txt
文件中读取数字的程序。 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.我的问题是将这个文件放在哪里,或者如何使用相对路径引用它以在不使用绝对路径的情况下访问该文件。
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");
for MyFile1, or对于 MyFile1,或
new File("./res/files/MyFile2.txt");
for MyFile2.对于 MyFile2。
If you have a multi-project setup, it may not be obvious what the "root" directory is for a relative path.如果您有一个多项目设置,则相对路径的“根”目录可能并不明显。 In that case, open the
Terminal
tab in your IntelliJ and see what directory it lands in. That is the "root" directory.在这种情况下,打开 IntelliJ 中的
Terminal
选项卡并查看它所在的目录。那是“根”目录。 Your relative path should start there.您的相对路径应该从那里开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.