问题
I have an initialization file (initialize.java) that pulls in data from fileInput.txt using a fileInputStream, but both of them are in different directories.
Project/library/initialize.java Project/resources/text/fileInput.txt
my code in initialize.java is:
FileInputStream fstream = new FileInputStream("/resources/text/fileInput.txt");
But the file cannot be read. I've also tried
FileInputStream fstream = new FileInputStream("./resources/text/fileInput.txt");
But that didn't work too.
How can I access the txt file and what's the difference between using "./resources" and "/resources"?
Thanks for reading this.
回答1:
The difference is huge. On linux/unix/macos the path starting with / starts from root directory. The path starting with ./ or without starting from current application directory. Call
System.out.println(new File("."). getAbsolutePath())
to check where you are?
回答2:
FileInputStream fstream = new FileInputStream("resources/text/fileInput.txt");
Tried this?
回答3:
"./resources/text/fileInput.txt"
or "resources/text/fileInput.txt"
works,
but "/resources/text/fileInput.txt"
doesn't.
Note: This is valid if the folder named "resources" is located under the root directory of your project.
回答4:
As the other answers suggest, the path you pass to FileInputStream depends on the OS and also if the path is a relative or an absolute path. Another way of reading the file is to use Class.getResourceAsStream()
instead. e.g.
InputStream is = this.getClass().getResourceAsStream("/resources/text/fileInput.txt")
For the above to work, you need to have the parent folder of /resources
in the classpath. For more information on how getResourceAsStream works, see SO question
来源:https://stackoverflow.com/questions/9679867/selecting-a-file-in-another-directory-for-a-bufferedreader