简体   繁体   English

使用 IntelliJ IDEA 在 Java 中引用具有相对路径的文本文件

[英]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。

You need to start your path from src.您需要从 src 开始您的路径。 "src/your/path/file.txt". “src/你的/路径/file.txt”。 See my answer here在这里看到我的答案

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM