Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equivalent to Files.readAllLines() for InputStream or Reader?

Tags:

java

jar

nio2

I have a file that I've been reading into a List via the following method:

List<String> doc = java.nio.file.Files.readAllLines(new File("/path/to/src/resources/citylist.csv").toPath(), StandardCharsets.UTF_8); 

Is there any nice (single-line) Java 7/8/nio2 way to pull off the same feat with a file that's inside an executable Jar (and presumably, has to be read with an InputStream)? Perhaps a way to open an InputStream via the classloader, then somehow coerce/transform/wrap it into a Path object? Or some new subclass of InputStream or Reader that contains an equivalent to File.readAllLines(...)?

I know I could do it the traditional way in a half page of code, or via some external library... but before I do, I want to make sure that recent releases of Java can't already do it "out of the box".

like image 915
Bitbang3r Avatar asked Mar 26 '15 15:03

Bitbang3r


People also ask

How do I use .readAllLines in java?

To read all lines from a file, we can use the Files. readAllLines() method. It takes the path to the file and the charset to use for decoding from bytes to characters. It returns the lines from the file as a list and throws an IOException if an I/O error occurs reading from the stream.

What is the difference between InputStream and reader?

Reader is Character Based, it can be used to read or write characters. FileInputStream is Byte Based, it can be used to read bytes. FileReader is Character Based, it can be used to read characters. FileInputStream is used for reading binary files.


2 Answers

An InputStream represents a stream of bytes. Those bytes don't necessarily form (text) content that can be read line by line.

If you know that the InputStream can be interpreted as text, you can wrap it in a InputStreamReader and use BufferedReader#lines() to consume it line by line.

try (InputStream resource = Example.class.getResourceAsStream("resource")) {   List<String> doc =       new BufferedReader(new InputStreamReader(resource,           StandardCharsets.UTF_8)).lines().collect(Collectors.toList()); } 
like image 149
Sotirios Delimanolis Avatar answered Oct 01 '22 06:10

Sotirios Delimanolis


You can use Apache Commons IOUtils#readLines:

List<String> doc = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);

like image 42
splintor Avatar answered Oct 01 '22 07:10

splintor