Java, reading a file from current directory?
Asked Answered
B

8

98

I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run).

In other words, if the user specifies the file name to be "myFile.txt", and that file is already in the current directory:

reader = new BufferedReader(new FileReader("myFile.txt"));

does not work. Why?

I'm running it in windows.

Bega answered 26/9, 2009 at 3:55 Comment(1)
This is same in Linux tooLiaotung
H
63

The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)

You can load files from the same directory* as the .class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.


*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.

Holeproof answered 26/9, 2009 at 4:24 Comment(3)
+1. If you're running an IDE like Eclipse or Idea, current directory will be the project directory, not the compiler output.Wildee
@piiligrim, depends on your launch configurationValkyrie
@DenisTulskiy I am working on Eclipse as same coding as the example person did. Mine is still not working, Why is that?Unconformable
D
97

Try

System.getProperty("user.dir")

It returns the current working directory.

Defunct answered 26/9, 2009 at 4:32 Comment(2)
but it returns only the path till root directory of project. how we can get path of current package in main method of javaCharlatan
@TaimoorChangaiz, System.getProperty("user.dir") + "\\src\\main\\java\\" + "Winners.txt"Solly
H
63

The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)

You can load files from the same directory* as the .class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.


*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.

Holeproof answered 26/9, 2009 at 4:24 Comment(3)
+1. If you're running an IDE like Eclipse or Idea, current directory will be the project directory, not the compiler output.Wildee
@piiligrim, depends on your launch configurationValkyrie
@DenisTulskiy I am working on Eclipse as same coding as the example person did. Mine is still not working, Why is that?Unconformable
A
43

None of the above answer works for me. Here is what works for me.

Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:

URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));
Authorship answered 21/5, 2015 at 10:49 Comment(2)
Can't access the file. Giving NullPointerException in path.getFile.Besant
This worked for me thanks. I suggest you write the first code like this: URL path = JAVA_FILE_NAME.class.getResource("myFile.txt");Keyway
S
24

Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in

----src
--------package1
------------myfile.txt
------------Prog.java

you can specify its path as "src/package1/myfile.txt" from Prog.java

Sparke answered 9/12, 2016 at 5:51 Comment(0)
G
8

Thanks @Laurence Gonsalves your answer helped me a lot. your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:

public class Run {
public static void main(String[] args) {
    File inputFile = new File("./src/main/java/input.txt");
    try {
        Scanner reader = new Scanner(inputFile);
        while (reader.hasNextLine()) {
            String data = reader.nextLine();
            System.out.println(data);
            
        }
        reader.close();
    } catch (FileNotFoundException e) {
        System.out.println("scanner error");
        e.printStackTrace();
    }
}

}

While my input.txt file is in same directory.

enter image description here

Genro answered 29/1, 2021 at 12:32 Comment(0)
S
6

If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:

URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
     //The file was not found, insert error handling here
}
File f = new File(path.toURI());

reader = new BufferedReader(new FileReader(f));
Sponsor answered 31/5, 2012 at 9:19 Comment(0)
F
2

Try this:

BufferedReader br = new BufferedReader(new FileReader("java_module_name/src/file_name.txt"));
Footmark answered 13/4, 2018 at 1:54 Comment(0)
T
1

try using "." E.g.

File currentDirectory = new File(".");

This worked for me

Thermoelectricity answered 10/3, 2020 at 0:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.