Reputation: 641
I have a method using the code below based on other resources how to iterate a file using a Java 8 stream:
String result = "";
try (Stream<String> stream = Files.lines(Paths.get("/home/user/file.txt"))) {
stream.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
However, I want to save the lines to += a string, instead of console.
I have tried these 2 below but neither pass IDE validation:
stream.forEach(thisString -> result += thisString);
stream.forEach(result += this);
stream.forEach(result::this);
What is the proper way to append each result from the foreach loop to a String object?
Upvotes: 2
Views: 1348
Reputation: 11040
If you just want to read the whole file as String, there is no need to use a Stream. If you are using Java 11, you can just use Files.readString()
:
try {
String result = Files.readString(Paths.get("/home/user/file.txt"));
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
If you need a Java 8 solution, see Holger's comment.
Upvotes: 3
Reputation: 20914
Hadi J has given you the answer in his comment
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FileJoin {
public static void main(String[] args) {
String result = "";
try (Stream<String> stream = Files.lines(Paths.get("/home/user/file.txt"))) {
result = stream.collect(Collectors.joining());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(result);
}
}
Upvotes: 2