tags:

views:

598

answers:

2

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.

+5  A: 

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.

Laurence Gonsalves
+1. If you're running an IDE like Eclipse or Idea, current directory will be the project directory, not the compiler output.
tulskiy
@piiligrim, depends on your launch configuration
Thorbjørn Ravn Andersen
+4  A: 

Try

System.getProperty("user.dir")

It returns the current working directory.

Joonas Pulakka