How do you read input from Java System.in in a Java program?

I want to run my program using:

java myProg < file

where file should be read as a string and passed to the main method in myProg. Any suggestions?

Hey, from my experience, the simplest way to read input from java system.in when running your program with java myProg < file is by using a Scanner. It’s pretty straightforward. Here’s a quick example:

import java.util.Scanner;

public class MyProg {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder content = new StringBuilder();
        
        while (scanner.hasNextLine()) {
            content.append(scanner.nextLine()).append("\n");
        }
        
        scanner.close();
        System.out.println("File Content:\n" + content);
    }
}

This code will read the entire file line by line and store it in a StringBuilder. You can process it as you want later. Works well for most cases, especially for simpler tasks.

That’s a great approach, Yanisleidi! I’ve used Scanner too, but if you’re working with large files or looking for something a bit more efficient, I’d suggest trying BufferedReader. It’s faster because it reads the input in larger chunks rather than line-by-line. Here’s how you can do it:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MyProg {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder content = new StringBuilder();
        String line;
        
        while ((line = reader.readLine()) != null) {
            content.append(line).append("\n");
        }

        System.out.println("File Content:\n" + content);
    }
}

This is definitely a better choice for larger files as it handles buffering efficiently. You won’t run into performance bottlenecks when dealing with huge amounts of data, and it’s pretty simple too.

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.