InputStream from relative path
Asked Answered
G

5

70

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!

Glossa answered 7/10, 2011 at 19:59 Comment(1)
Thats not a relative path. That's an absolute path.Pul
S
95

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.

Sissy answered 7/10, 2011 at 20:1 Comment(0)
G
100
InputStream inputStream = Files.newInputStream(Path);
Glossectomy answered 30/7, 2016 at 17:37 Comment(2)
flawless answer!Joyless
Consider using buffered version for better efficiency: linkNucleus
S
95

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.

Sissy answered 7/10, 2011 at 20:1 Comment(0)
A
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.

Almucantar answered 3/9, 2014 at 4:57 Comment(1)
The existing answers already covers the question in a more simple way.Hunkydory
A
4

Found this to be more elegant and less typing.

import java.nio.file.Files;
import java.nio.file.Paths;

InputStream inputStream = Files.newInputStream(Paths.get("src/test/resources/sampleFile.csv"));

Note: In my case, file was very small (used for Unit Tests), but prefer to use BufferedInputStream for better efficiency.

Aileen answered 13/7, 2022 at 9:14 Comment(0)
W
2

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

Weiland answered 7/10, 2011 at 20:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.