Get file from relative path in windows

2019-09-20 14:27发布

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?

3条回答
Juvenile、少年°
2楼-- · 2019-09-20 14:31

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(...)

查看更多
姐就是有狂的资本
3楼-- · 2019-09-20 14:33

It seems that you are running your application on any server.
So when you run it on server, application will take path relative to that server's root directory (May be /bin or something else depending on your server).
When you run it as standalone java program it take path relative to where standalone program is executing.
So if you want to run it on server give path relative to server's root directory.
Like:-
File initialFile = new File("<Path after Server root>/test/java/com/pro/mockfiles/My-DOC-FILE.doc");

<Server root> can be a path after C:/Myserver/bin

查看更多
趁早两清
4楼-- · 2019-09-20 14:56

Event though relative paths may work in Java, I personally would recommend against using them. The mean reason being that the 'relative' path to a file changes depending on the working directory of Java. If you start the application from 'c:\tmp' then the relative path would be different then when you start it from 'c:\test'. Even if the application is located in 'c:\myApp'.

But if you want to use it first figure out where your applications was started from (called the working directory) by executing the code below:

 System.out.println(Paths.get("").toAbsolutePath().toString());

After this change your relative path according to the difference between the working directory and the file you want.

As a side note I noticed the file is stored in the classpath. So you may want to look into the ClassLoader to acces the file rather then using the file system. You can do that (in case the code is executed in a test) by the following code:

MyClass.class.getClassLoader().getResourceAsStream("/com/pro/mockfiles/My-DOC-FILE.doc");

This code is more robust as it will work no matter where the application is started from.

查看更多
登录 后发表回答