← Java from Scratch Lesson 60 of 88 · 10 XP

I/O streams

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A stream is a sequence of data that's read or written in order, like a tape. java.io has two families:

bytes (pictures, sound, anything) characters (text)
reading InputStream Reader
writing OutputStream Writer

The concrete classes say "where from": FileInputStream (a file), ByteArrayInputStream (an array in memory), and System.in is an InputStream too. Streams wrap each other, adding abilities:

new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))
//  a buffer, lines   ← bytes → characters by the encoding ← raw keyboard bytes

What's under the hood. A byte and a character are different things. In UTF-8 a Latin letter is 1 byte, an accented, Greek or Cyrillic letter is 2, an emoji is 4. InputStreamReader builds characters out of bytes by the rules of the encoding. That's why the length of a text in characters and in bytes differs — and it's always worth specifying the encoding explicitly.

Task. Read the whole input as bytes (System.in.readAllBytes()) and print: the number of bytes, the number of characters (new String(bytes, StandardCharsets.UTF_8).length()) and the number of lines.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.