56

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!

İsmail Y.
  • 2,778
  • 5
  • 19
  • 21
Allan Jiang
  • 10,503
  • 26
  • 100
  • 158

4 Answers4

86

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.

Tomasz Nurkiewicz
  • 324,247
  • 67
  • 682
  • 662
78
InputStream inputStream = Files.newInputStream(Path);
Shakirov Ramil
  • 1,051
  • 8
  • 11
  • flawless answer! – Gaurav Jul 14 '20 at 11:42
  • Consider using buffered version for better efficiency: [link](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#newBufferedReader(java.nio.file.Path)) – SilverFox Oct 02 '20 at 09:48
4

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.

Ahmed Ashour
  • 4,462
  • 10
  • 33
  • 49
2

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

michael667
  • 3,216
  • 22
  • 32