I am not understanding why the following code seems to skip the first input character.
import java.io.*;
import java.util.Arrays;
public class Input
{
public static void main (String args[])
{
try {
echo(System.in);
}
catch (IOException e) {
e.printStackTrace();
}
}
static void echo(InputStream stream) throws IOException
{
byte[] input = new byte[10];
char[] inputChar = new char[10];
int current;
while ((current = stream.read()) > 0){
stream.read(input);
int i = 0;
while (input[i] != 0) {
inputChar[i] = (char)input[i];
if (i < 9) {
i++;
}
else {
break;
}
}
System.out.println(Arrays.toString(inputChar));
}
}
}
If I give input as "1234567890" the output I get is "[2, 3, 4, 5, 6, 7, 8, 9, 0,]" The last character in inputChar seems to be blank. However, if it did not read any byte into input[9], it should be null character (ASCII 0). If I give an input which is less than 10 characters in length I get null character for the remaining positions in inputChar. So I am not sure what is going on here.
while ((current = stream.read()) > 0){
You have your first read here, you're not making any use of it but it's an actual read that will advance the "position" in your stream.