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!
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.
InputStream inputStream = Files.newInputStream(Path);
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.
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.
new FileInputStream("your_relative_path")
will be relative to the current working directory.
精彩评论