2

I've tried to open a file, using a relative path, with my file is located in the root folder of my project.

BufferedReader reader = new BufferedReader(new FileReader("text.h"));

That didn't work.

So I printed the working directory, but this leads me to the directory in which eclipse is installed.

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

My project structure:

Project
       --bin
       --core
           text.h
           --src
              text.h 
              --com
                 --home
                     --core
                         Main.java
                         text.h
       --editor
       --ui
       text.h

I've copied the text file in different locations, inside the my project directory and I've tried different paths, but none has worked.

If I copy the file inside the directory where Eclipse is installed, then I can read the file with the following path.

BufferedReader reader = new BufferedReader(new FileReader("text.h"));

How can I read the file from the root folder of my project ?

seby598
  • 141
  • 4
  • 11
  • 1
    using "/" you can access root folder. Show us your project structure. – Florescent Ticker Jun 17 '14 at 11:44
  • System.getProperty("user.dir") can show you your current working directory. If that path is someplace lower than your working dir then you might have to append some ../.. to the File constructor arg – omu_negru Jun 17 '14 at 11:50
  • Maybe also http://stackoverflow.com/questions/3209901/absolute-path-of-projects-folder-in-java helps? – godfatherofpolka Jun 17 '14 at 11:51
  • If you don't want to work with absolute paths, you can add a system variable with the Eclipse workspace for value. Then, add the root folder of your projects to the variable. It doesn't make the program less portable if you need to look for specific abs paths. – Alex Jun 17 '14 at 11:52
  • @omu_negru System.getProperty("user.dir"); and System.out.println(new File(".").getAbsolutePath()); print the same path. – seby598 Jun 17 '14 at 11:53

2 Answers2

2
String workingDir = System.getProperty("user.dir");


BufferedReader reader = new BufferedReader(new FileReader(workingDir+"\text.h"));

workingDir's value gives a path of current working directory

try this one it may help you

Nirav Prajapati
  • 2,987
  • 27
  • 32
1
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
System.out.println("URL " + url.toExternalForm());

URL file:/D:/workspace/myproject/bin/

or when jar clicked:

URL file:jar:/D:/workspace/myproject/bin/myproject.jar!/....
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Don't I need to call the getClass() function on an object? I've tried URL url = Main.class.getClass().getProtectionDomain().getCodeSource().getLocation(), but I get a NullPointerException. – seby598 Jun 17 '14 at 12:18
  • `MainClass.class.getProtectionDomain()...` of course. ;) otherwise `Class.class`. – Joop Eggen Jun 17 '14 at 13:21