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:
"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:
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--
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With