11

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?

Lesmana
  • 25,663
  • 9
  • 82
  • 87
Scicare
  • 833
  • 5
  • 13
  • 26
  • 1
    The answer to this question will answer yours as well, though not technically a dup: http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream – Kirk Woll Oct 08 '10 at 01:49

2 Answers2

22

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

Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232
  • 1
    @alex I'm assuming it's the class *from* which you're trying to gain access to another package. If Class A, Package A is trying to access a file in Package B, `MyClass` would be Class A, Package A. That's my interpretation. – Mathomatic Jun 16 '17 at 19:34
1

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

pf_miles
  • 907
  • 1
  • 8
  • 17