Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file (e.g txt file) from another java package withouth specifying the absolute path?

Tags:

java

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?

like image 335
Scicare Avatar asked Oct 08 '10 01:10

Scicare


2 Answers

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! :)

like image 123
Pablo Fernandez Avatar answered Oct 13 '22 09:10

Pablo Fernandez


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'.

like image 28
pf_miles Avatar answered Oct 13 '22 09:10

pf_miles