Scicare
Scicare

Reputation: 833

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 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?

Upvotes: 11

Views: 35768

Answers (2)

pf_miles
pf_miles

Reputation: 927

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

Upvotes: 1

Pablo Fernandez
Pablo Fernandez

Reputation: 105220

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

Upvotes: 22

Related Questions