AnonymousAlias
AnonymousAlias

Reputation: 1399

Why won't input stream find a file outside of the class folder

I want to want to use input stream with a file "NewFile.java", the code I have works fine if the file is situated in the same folder as the .class file that is performing the action. But once I move I get null reference.

I have tried using absolute and relative paths with and without a '/' at the start.

InputStream in = getClass()
                .getResourceAsStream("NewFile.java");

I would like to source the file when it is located in the root directory of the project.

Upvotes: 2

Views: 1799

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109567

There is a distinction between files on the file system, and resources, on the class path. In general a .java source file won't be copied/added to the class path.

For a class foo.bar.Baz and a resource foo/bar/images/test.png one can use

Baz.class.getResourceAsStream("images/test.png")
Baz.class.getResourceAsStream("/foo/bar/images/test.png")

As you see the paths are class paths, possibly inside .jar files.

Use file system paths:

Path path = Paths.get(".../src/main/java/foo/bar/Baz.java");
InputStream in = Files.newInputStream(path);
List<String> lines = Files.readAllLines(path);
List<String> lines = Files.readAllLines(path, StandardCharsets.ISO_8859_1);
Files.copy(path, ...);

Upvotes: 1

Michael B.
Michael B.

Reputation: 64

Better use InputStream in= new FileInputStream(new File("path/to/yourfile"));

The way you are using it now is as a resource which has to be in the class path.

Upvotes: 3

Ctx
Ctx

Reputation: 18420

getResourceAsStream() is not meant to open arbitrary files in the filesystem, but opens resource files located in java packages. So the name "/com/foo/NewFile.java" would look for "NewFile.java" in the package "com.foo". You cannot open a resource file outside a package using this method.

Upvotes: 2

Related Questions