EOF is defined for C ++ itself
But if there is no EOF in JAVA?
Sample picture
Asked
Active
Viewed 88 times
-1

Software Engineer
- 15,457
- 7
- 74
- 102

PonyYA_OuO
- 11
-
1Does this answer your question? [reading input till EOF in java](https://stackoverflow.com/questions/13927326/reading-input-till-eof-in-java) – Eggcellentos Mar 29 '20 at 15:15
-
or https://stackoverflow.com/questions/36515937/how-to-detect-eof-in-java – Eggcellentos Mar 29 '20 at 15:18
-
@ghosh Scanner is line buffered and parses. That is not exactly the OP's wish: reading a byte or end-of-file. – Joop Eggen Mar 29 '20 at 15:27
-
1We far prefer pasted code rather than screenshots. – Software Engineer Mar 29 '20 at 15:34
-
This looks to me like it may be relevant: [How to read a single char from the console in Java (as the user types it)?](https://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it/6876253) – Abra Mar 29 '20 at 15:58
1 Answers
1
Java InputStream#read
will behave exactly so, returning -1 (C/C++) EOF or an other int in the byte range, unsigned as 0 .. 255.
However String
(with Reader
and Writer
) in java is for Unicode text, char
being a 2-byte UTF16 value. Input-
and OutputStream
and byte
is for binary data, needing some encoding (Charset
) to convert it to String
.
byte[] read(InputStream in) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while ((c = in.read()) != -1) {
baos.write((byte) c); // Cast not needed, as int.
}
return baos.toByteArray();
}
String read(InputStream in) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while ((c = in.read()) != -1) {
baos.write((byte) c); // Cast not needed, as int.
}
return baos.toString("UTF-8"); // Conversion provided.
}

Joop Eggen
- 107,315
- 7
- 83
- 138