Reference a Text File with relative path in Java with the IntelliJ IDEA
Asked Answered
G

5

10

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.

Guyenne answered 10/6, 2015 at 19:12 Comment(0)
H
19

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

new File("./res/files/MyFile2.txt"); for MyFile2.

Hieroglyphic answered 10/6, 2015 at 20:29 Comment(1)
And of course import your text file to your working directoryHieroglyphic
C
7

You need to start your path from src. "src/your/path/file.txt". See my answer here

Crabstick answered 19/5, 2018 at 16:11 Comment(0)
D
5

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. Your relative path should start there.

Desdamonna answered 24/8, 2020 at 4:12 Comment(1)
This was the answer that I am looking for! Thanks @Big PumpkinBimetallism
P
0

@Big Pumpkin Not sure about the terminal showing me the path of the "root". But it does turn out to be the top most directory in a multi-module project.

enter image description here

Pterous answered 12/3, 2023 at 1:46 Comment(0)
K
0

If file1.txt in 'src' it will have path as "src\main\java\file1.txt". Relative path starts from src.

Kiaochow answered 26/8, 2023 at 18:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.