简体   繁体   中英

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.

在此处输入图片说明

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.

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

PS this is all untested so it might not work.

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

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.

您必须将文件声明为新文件:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM