Lesson 3 | The write() method |
Objective | Write a program that echoes System.in to System.out. |
Java write() Method to echo System.in to System.out
The fundamental method of the OutputStream
class is write()
.
This method writes a single unsigned byte of data whose value should be between 0 and 255. If you pass a number larger than 255 or smaller than zero,
it is reduced modulo 256 before being written.
The following code fragment prints the printable ASCII characters between 32 and 127 on System.out
:
for (int i = 32; i < 128; i++) {
System.out.write(i);
System.out.println();
}
In this example, the console interprets the numeric values as ASCII characters, not as numbers.
This is a feature of the console, not of the OutputStream
class or the specific subclass of which System.out
is an instance. The write()
method merely sends a particular bit pattern to a particular output stream.
How that bit pattern is interpreted depends on what's connected to the other end of the stream.
The write()
method is declared to throw an IOException
. java.io.IOException
is a checked exception so you will need to wrap most calls to this method in a try-catch
block or declare that your own method throws IOException
.
try-catch block
The write()
method is declared to throw an IOException
.
java.io.IOException
is a checked exception so you will need to wrap most calls to this method in a
try-catch
block or declare that your own method throws IOException
.
try {
for (int i = 32; i < 128; i++) {
os.write(i);
}
catch (IOException e) {
System.err.println(e);
}
The one notable exception is System.out
. For reasons that will be discussed in the next lesson,
no method invocation on System.out
will ever throw an exception.
Answer: A, E
Explanation:
Option A is correct because at line 5,
public static void main(String[] args) throws IOException {
needs the java.io.IOException class and we need the java.io.FileOutputStream class to write data to files (line 8), so we need these two classes to make this code work. We can achieve this by importing all classes in java.io package by using import java.io.*; since it will import all the classes including these two, so option E is correct.
Option B is incorrect because we need to import both FileOutputStream and IOException classes or none of these will ensure correct compilation.
So answers B, C and D are incorrect.
See http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html for more information.
The correct answer is: We have to import java.io.FileOutputStream and java.io.IOException in order to make compilation succeed.
Changing import java.io.FileInputStream; to import java.io.*; will make this code work.
Java Write Method - Exercise
Click on the Exercise link below to write a program that reads data from
System.in
, and copies each byte read to
System.out
as a byte.
Java Write Method - Exercise