1

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.

AnonymousAlias
  • 1,149
  • 2
  • 27
  • 68

3 Answers3

2

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.

Ctx
  • 18,090
  • 24
  • 36
  • 51
  • 1
    ...replace "java packages" with "classpath", then I agree :) (some people could consider "no/empty package"/"the default package" as "outside" :) – xerx593 Jan 11 '19 at 13:12
  • @xerx593 Hm, where exactly do you see the difference? – Ctx Jan 11 '19 at 13:21
2

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.

Michael B.
  • 54
  • 5
  • This seems like the most straight forward answer and it worked, I have a question though. If this application would be running from an online repository can we still use this with the file path as a parameter? If we use the relative path eg. `InputStream in1= new FileInputStream(new File("NewFile.java"));` – AnonymousAlias Jan 11 '19 at 13:33
1

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, ...);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138