Search code examples
javafileiopath

Finding the right Path


I want to generate a PDF with Apache PDFBox and put it under docs/file1.pdf. The folder docs is already created, but I don't know how to access it from Java.

My project structure looks like this:

  • build
  • nbprojects
  • docs
  • src <-- this is where the generated files belong

    • java
      • generator
        • generator.java <-- this is where the files are being generated
  • [some other folders]

When I try:

System.getProperty("user.dir");

I get (I'm on Linux):

/home/user1/.netbeans/9.0/config/GF_5.0/domain1/config

My guess was going 3 levels up:

../../../docs/file1.pdf

But it says

java.io.FileNotFoundException: ../../../docs/file1.pdf was not found

Question: How can I access docs from src/java/generator/generator.java?


Solution

  • One way is to use absolute path. Or you can use this print statement to know your current directory as per your java program,

    System.out.println("Current Dir: " + new File(".").getAbsolutePath());
    

    It will print something like,

    \pkr\work7\ws\test\.
    

    Once you know this path, you can build your path correctly by putting .. and be able to correctly read your file.