Tuesday 13 March 2012

Read a file in Java - oneliner?

Can anyone read a file in Java using the standard libraries in a single line?

This was the best I could do:

1:      public static List<String> readRows(InputStream stream) {  
2:          try {  
3:              byte[] data = new byte[stream.available()];  
4:              new DataInputStream(stream).readFully(data);  
5:              return Arrays.asList(new String(data).split("\\r\\n|\\n|\\r"));  
6:          } catch (IOException e) {  
7:              throw new IllegalStateException(e);  
8:          }  
9:      }  

It has the obvious caveat that stream.available() only returns an estimate for the size of the stream so this isn't suitable for production code.

This is one line longer and the more sensible choice, though I am being deliberately terse with the for loop:

1:      public static List<String> readRows2(InputStream stream) {  
2:          try {  
3:              LinkedList<String> rows = new LinkedList<String>();  
4:              BufferedReader reader = new BufferedReader(new InputStreamReader(stream));  
5:              for (String data = ""; (data = reader.readLine()) != null; rows.add(data));  
6:              return rows;  
7:          } catch (IOException e) {  
8:              throw new IllegalStateException(e);  
9:          }  
10:      }  

I'm aware that Guava and Apache Commons have utilities for this problem, so those would be also good choices.

No comments:

Post a Comment