Both of those methods are solid, but if you’re using Java 8 or later, there’s a cleaner and more modern way to handle this with Stream and Collectors.joining(). It’s a one-liner that’s easy to use and super efficient for medium-sized files. Here’s an example of how to do it:
import java.io.IOException;
import java.util.stream.Collectors;
import java.nio.charset.StandardCharsets;
public class MyProg {
public static void main(String[] args) throws IOException {
String content = new String(System.in.readAllBytes(), StandardCharsets.UTF_8);
System.out.println("File Content:\n" + content);
}
}
This code reads everything at once using System.in.readAllBytes(), which means you get the entire input in one go. It’s perfect for smaller to medium-sized files, and it makes the code really clean and concise. Definitely a nice alternative when you don’t need to worry about handling each line separately.