Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java IO: Why does the numerical representation of line feed appear on the console when reading from stdin?

Tags:

java

eclipse

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

like image 962
cluster1 Avatar asked Mar 10 '23 00:03

cluster1


1 Answers

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--

like image 72
Ryan Leach Avatar answered Apr 26 '23 14:04

Ryan Leach