I have stored non-java files in a package. 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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With