Albon Wu Albon Wu - 21 days ago 7
Java Question

How can I convert an entire input file into a string?

In Java, how would I convert an entire input file into one

String
?

In other words, if I have an input file
"test.in"
:

c++
java
python
test


then I want to create a
String
containing
"c++javapythontest"
.

I thought of something along the lines of

Scanner input = new Scanner(new File("test.in"));
while(input.hasNext()){
String test = test + input.nextLine();
}


but that doesn't seem to work.

Is there an efficient way to do this?

Answer

To read file contents, discarding newline chars:

String contents = Files.lines(Paths.get"test.in")).collect(Collectors.joining());

I think you needed to test for hasNextLine(), and your code's performance suffers from the creation of so many objects when you concatenate strings like that. If you changed your code to use a StringBuilder, it would run much faster.