Java, reading a file from current directory?

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.


Try

System.getProperty("user.dir")

It returns the current working directory.


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.


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));