InputStream from relative path

111,778

Solution 1

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

InputStream inputStream = Files.newInputStream(Path);

Solution 3

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

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

Share:
111,778
Allan Jiang
Author by

Allan Jiang

Updated on July 09, 2022

Comments

  • Allan Jiang
    Allan Jiang almost 2 years

    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!

  • Dolda2000
    Dolda2000 over 9 years
    The existing answers already covers the question in a more simple way.
  • Gaurav
    Gaurav almost 4 years
    flawless answer!
  • SilverFox
    SilverFox over 3 years
    Consider using buffered version for better efficiency: link