4

Just for getting a better understanding of what I've heard in a lecture (about Java Input- and Output-Stream) I've made myself this tiny program:

public static void main (String[] args) throws Exception {
    int input;
    FileOutputStream fos = new FileOutputStream("test.txt");

    // 95 is the underscore-char ( _ ). I use it
    //  for to finish it reception of input.
    while ((input = System.in.read()) != 95) {
        fos.write(input);
        out.println(input);
    }

    out.println("- Finished -");

    fos.close();
}

It prints the numerical representation of the character I've just typed to stdout. It works basically but here is what I see in Eclipse:

Screeshot Eclipse

"10" is the decimal ASCII representation of the line feed.

Okay. I've pressed the enter-key for to finish the iteration.

But why does this second value appear too?

I would expect only the first key (the actual character) to appear.

If somehow can explain the issue then I would appreciate his / her answer.

@Sanket Makani Here's the corresponding content of the text-file "text.txt":

2
3
A
a

In Eclipse:

Screenshot

michael.zech
  • 3,524
  • 5
  • 19
  • 37

3 Answers3

3

InputStreams can be used for binary formats, binary formats don't care about filtering new line characters.

You will either need to filter them yourself, or use a buffered reader/scanner and read line, then iterate along the characters in the string.

https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()

Shows that it indeed does only read one character at a time, however the eclipse terminal may not be forwarding the data entered until you press enter.

When that happens your loop is running twice.

Scanner docs: https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextLine--

Ryan The Leach
  • 3,719
  • 2
  • 26
  • 57
  • I thought System.in.read() would read only one byte / character from stdin. But that was a mistake. If you enter a lot of characters (abcdefg ...) together and then press enter then all those characters a returned in there decimal representation. The line feed representation included as well. Do you know how many characters System.in.read() reads maximal? – michael.zech May 29 '17 at 07:31
  • "... the eclipse terminal may not be forwarding the data entered until you press enter." That explains it. Thanks a lot. – michael.zech May 29 '17 at 07:44
3

As you said so yourself, its treating the newline as part of your input as well.

Please refer to this question on SO, it might be helpful to what you wish to accomplish.

How to read integer value from the standard input in Java

Sadiq Ali
  • 1,142
  • 2
  • 12
  • 22
1

The newline is part of your input stream, so System.in.read() sees it as well. If you only want to print the character codes of characters within the line, you need to filter out the line feed characters.