0

I'm working with Eclipse and there, I have Java Project with the name "Test" which also contains text files. A class in this Project should be able to read in one of these files with a BufferedReader. This is my current code for that:

BufferedReader in = new BufferedReader(new FileReader("C:/Users/workspace/Test/testFile.txt"));

My file is always in the Project, but when I move the Project to another path, the file path changes, too, so I have to adjust the code with the new path. I dont't want that, because it's impractical, so what can I do? How can I get the path of the Project?

LCP
  • 45
  • 1
  • 3
  • 10
  • Why do you have to move the file at first if it is required for the project?It is better to add the file as a resource to your project and access from the current path. – Praburaj Jan 04 '17 at 10:35
  • 1
    A simple solution would be to use relative path like "./testFile.txt". Keep in mind that this is relative to the directory from where you started the application. – Zhivko Delchev Jan 04 '17 at 10:36
  • I move my Project which contains the file. – LCP Jan 04 '17 at 10:37
  • In this case you can put the file in the resource folder of the project and use the class loader to get the file from there. – Zhivko Delchev Jan 04 '17 at 10:39

2 Answers2

1

You can add file to resources folder and read like

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());
Reva
  • 118
  • 2
  • 7
  • I have created a new "resources" folder and put the file there. Then I used your code and do in = new BufferedReader(new FileReader(file)); but it doesn't works! – LCP Jan 04 '17 at 12:05
  • 1
    You need to add the resources folder to the build path as well: http://stackoverflow.com/questions/27934796/how-do-i-add-a-resources-folder-to-my-java-project-in-eclipse – Zhivko Delchev Jan 04 '17 at 14:50
0

Try something like this:

File currentDirFile = new File(".");
String fileDir = currentDirFile.getAbsolutePath();
Thorviory
  • 67
  • 12