Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most concise way to read the contents of a file/input stream in Java?

Tags:

java

What ist most concise way to read the contents of a file or input stream in Java? Do I always have to create a buffer, read (at most) line by line and so on or is there a more concise way? I wish I could do just

String content = new File("test.txt").readFully();
like image 215
cretzel Avatar asked Dec 05 '22 07:12

cretzel


1 Answers

Use the Apache Commons IOUtils package. In particular the IOUtils class provides a set of methods to read from streams, readers etc. and handle all the exceptions etc.

e.g.

InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.readLines(is)
like image 160
Brian Agnew Avatar answered May 21 '23 17:05

Brian Agnew