Jin
Jin

Reputation: 165

Missing first character while reading from inputstream

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.

Upvotes: 2

Views: 2313

Answers (3)

Dinesh Kc
Dinesh Kc

Reputation: 51

I fixed the issue with do while loop instead of while loop .

Here is the complete code for mine:

    File f = new File("emp.doc");
    FileInputStream fi = new FileInputStream(f);
    do {
        System.out.println("Character is ; "+ (char)fi.read());
    }while(fi.read() != -1);

Upvotes: 0

Anugoonj
Anugoonj

Reputation: 575

The stream.read() that is being used in the loop control reads the first character.

Upvotes: 0

Javadrien
Javadrien

Reputation: 201

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.

Upvotes: 8

Related Questions