R_FF92 R_FF92 - 1 year ago 61
Java Question

Correct path for reading lines of a file

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

for the class
. The file
is saved in the same directory as my Java class
. 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();


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

for(String line : zeilen){

} catch (IOException e) {


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

Answer Source

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


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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download