user4591549
user4591549

Reputation:

Reading Multi-Line Input From Command Line at once

I have a need for a simple class to read multi-line input at once. For example, reading these two lines at once from a buffer:

b8 b7

g8 g2

This code only inputs the first line from the buffer, and without the first character...

int avail = System.in.read();
byte[] buf = new byte[avail];
System.in.read(buf);
String s = new String(buf);
String[] lines = s.split("\n");

//System.out.println(lines);
        
for(int i=0; i<lines.length; i++) {
    System.out.println(lines[i]);
}

Upvotes: 0

Views: 1462

Answers (1)

mzc
mzc

Reputation: 3355

It's without first char because the first char is saved in avail as a result of the first read() call. Then you are creating a buffer with size of the ASCII value of the first char (which is not the buffer size that you want).

Better approach is to read the input line by line with a BufferedReader like this:

public class Main {
    public static void main(String[] args) throws Exception {
        try (BufferedReader input = new BufferedReader(new InputStreamReader(System.in))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = input.readLine()) != null) {
                if ("".equals(line)) break;
                sb.append(line).append('\n');
            }
            System.out.println(Arrays.toString(sb.toString().split("\n")));
        }
    }
}

Upvotes: 1

Related Questions