InputStream from relative path

JavaPathIoInputstreamRelative Path

Java Problem Overview


I have a relative file path (for example "/res/example.xls") and I would like to get an InputStream Object of that file from that path.

I checked the JavaDoc and did not find a constructor or method to get such an InputStream from a path/

Anyone has any idea? Please let me know!

Java Solutions


Solution 1 - Java

Use FileInputStream:

InputStream is = new FileInputStream("/res/example.xls");

But never read from raw file input stream as this is terribly slow. Wrap it with buffering decorator first:

new BufferedInputStream(is);

BTW leading slash means that the path is absolute, not relative.

Solution 2 - Java

InputStream inputStream = Files.newInputStream(Path);

Solution 3 - Java

Initialize a variable like: Path filePath, and then:

FileInputStream fileStream;
try {
    fileStream = new FileInputStream(filePath.toFile());
} catch (Exception e) {
	throw new RuntimeException(e);
}

Done ! Using Path you can have access to many useful methods.

Solution 4 - Java

new FileInputStream("your_relative_path") will be relative to the current working directory.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAllan JiangView Question on Stackoverflow
Solution 1 - JavaTomasz NurkiewiczView Answer on Stackoverflow
Solution 2 - JavaShakirov RamilView Answer on Stackoverflow
Solution 3 - JavaChristian CeballosView Answer on Stackoverflow
Solution 4 - Javamichael667View Answer on Stackoverflow