R_FF92 R_FF92 - 3 months ago 7
Java Question

Correct path for reading lines of a file

I am new in Java and I have a question regarding the method

readAlllines
for the class
Files
. The file
"Testfile.txt"
is saved in the same directory as my Java class
changeFiles
. I want to read the lines out of it.

Here is my example code:

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;



public class changeFiles {

public static void main(String[] args) {

File temp =new File("Testfile.txt");
Path p = temp.toPath();

try{

List<String> zeilen = Files.readAllLines(p);

for(String line : zeilen){
System.out.println(line);
}

} catch (IOException e) {
System.out.println(e);
}
}

}


Unfortunately, the method can't find the file. How do I get the correct path to my file in
readAllLines
?

Answer

You're trying to get file from working directory, check yours printing this in some way

System.getProperty("user.dir")

Place "Testfile.txt" there, run and enjoy.


Another solution will be put folder when reading file using File(folder, file) constructor:

// imagine your file is placed in: c:\tmp\Testfile.txt
final String folder = "C:\\tmp\\";
File temp = new File(folder, "Testfile.txt");

Or maybe merge both:

final String folder = System.getProperty("user.dir");
File temp = new File(folder, "Testfile.txt");
Comments