How to read a file (e.g txt file) from another java package withouth specifying the absolute path?
I have stored non-java files in a pac开发者_如何学Gokage. I want to read files from this package without specifying the absolute path to the file(e.g C:\etc\etc...). How should I do this?
Use getResourceAsStream
For example:
MyClass.class.getResourceAsStream("file.txt");
Will open file.txt
if it's in the same package that MyClass
Also:
MyClass.class.getResourceAsStream("/com/foo/bar/file.txt");
Will open file.txt
on package com.foo.bar
Good luck! :)
First, ensure that the package in which your files contained is in your app's classpath.. Though your didnt specifying the path of the files, you still have to obtain the files' paths to read them.Your know all your files' names and package name(s)? If so, your could try this to obtain a url of your file:
public class Test {
public static void main(String[] args) throws Exception {
URL f = Test.class.getClassLoader().getResource("resources/Test.txt");
System.out.println(f);
}
}
the code above obtains the url of file 'Test.txt' in another package named 'resources'.
精彩评论