sAm
sAm

Reputation: 321

Cannot access text file in java project

I am trying to access a text file, output.txt which is inside a project folder. The image below shows the folder structure.

enter image description here

String file=".\\testFiles\\output.txt";
BufferedReader br=new BufferedReader(new FileReader(file));

When I try to access that file using the code above, I get the following exception.

 java.io.FileNotFoundException: .\testFiles\output.txt (No such file or directory)

I have tried different file path formats but none have worked. I think the problem is with the file path format.

Thanks in advance.

Upvotes: 1

Views: 374

Answers (4)

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

I believe that your problem is due to the fact that you rely on a relative path as your path starts with a dot which means that it will by relative to the user directory (value of the system property user.dir) so I believe that your user directory is not what you expect. What you could do to debug is simply this:

System.out.println(new File(file).getAbsolutePath());

Thanks to this approach you will be able to quickly know if the absolute path is correct.

Upvotes: 1

andrei.serea
andrei.serea

Reputation: 960

Judging by the fact that you have a webcontent folder i presume this is a web project, possibly packaged as a war? In this case what you will want to do is package the respective files along with the classes and access it with something like this:

Thread.currentThread().getContextClassLoader().getResourceAsStream("output.txt")

The code above will work if you add the testFiles folder as a source folder (this means it will get packaged with the classes and be available at runtime)

The good thing is that this way the path can stay relative, no need to go absolute

Upvotes: 1

DerRKDCB
DerRKDCB

Reputation: 17

You must declare your file as a new file:

File yourFile = new File("testFiles/output.txt");

Upvotes: -2

Roan
Roan

Reputation: 1206

If I remember correctly you can get a folder/file in the current directory like so:

File folder = new File("testFiles");

Then you can open the file by getting the absolutePath and creating a new file with it, like so:

File file = new File(folder.getAbsoluteFile() + File.separator + "output.txt");

I'm not sure but I think you can also do:

File file = new File("testFiles/output.txt");

I hope this helps :)

P.S. this is all untested so it might not work.

Upvotes: 1

Related Questions