Search code examples
javainputstreamfileinputstream

Get file from relative path in windows


I am trying to access .doc a file from my project directory. I am getting an error when I use a relative path in windows. but it works fine when I get an absolute path.

File initialFile = new File("D:\\Demo\\src\\test\\java\\com\\pro\\mockfiles\\My-DOC-FILE.doc");
InputStream uploadStream = new FileInputStream(initialFile);

works fine but,

File initialFile = new File("test/java/com/pro/mockfiles/My-DOC-FILE.doc");
InputStream uploadStream = new FileInputStream(initialFile);

gives the following error

java.io.FileNotFoundException: test\java\com\pro\mockfiles\My-DOC-FILE.doc (The system cannot find the path specified)

I want to run with a relative path, can you help?


Solution

  • Here is an other solution, how to get the directory, the application was started in:

    String current_dir = System.getProperty("user.dir");

    After this the absolute path to the .doc can be built using the current working directory:

    Paths.get(current_dir, "test/java/com/pro/mockfiles/My-DOC-FILE.doc");

    with Paths.get(...)