Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

java - 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: testjavacompromockfilesMy-DOC-FILE.doc (The system cannot find the path specified)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: mp' then the relative path would be different then when you start it from 'c: est'. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...