Java reading a file from the current directory?

I need a java program that reads a user-specified file name from the current directory (the same directory in which the .class file is running).

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

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

does not work. Why?

I run it in windows.

+49
java
Sep 26 '09 at 3:55
source share
6 answers

The current directory does not (necessarily) have the directory in which the .class file is located. This is the working directory of the process. (i.e.: the directory you were in when you started the JVM)

You can upload files from the same directory as the .class file with getResourceAsStream () . This will give you an InputStream, which you can convert to a Reader using an InputStreamReader .

+37
Sep 26 '09 at 4:24
source share

Try

 System.getProperty("user.dir") 

It returns the current working directory.

+58
Sep 26 '09 at 4:32
source share

None of the above answers work for me. Here is what works for me.

Say your class name is Foo.java, to access the file 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)); 
+22
May 21 '15 at 10:49
source share

If you know that your file will live where your classes are, this directory will be in your class path. In this 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)); 
+4
May 31 '12 at 9:19 a.m.
source share

Files in your project are available to you in relation to your src folder. if you know which package or folder myfile.txt is located, let's say it is in

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

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

+2
Dec 09 '16 at 5:51 on
source share

This also works:

 Path file=Paths.get("Your file path"); InputStream is=Files.newInputStream(file); BufferedReader br=new BufferedReader(new InputStreamReader(is)); 
-3
Aug 10 '15 at 5:56
source share



All Articles