J2EEOnline
GofPatterns OOPortal
prev next prev next
  Course navigation
 
Lesson 3
Objective
Efficient input
Write a program that uses a byte array buffer to copy data from System.in to System.out.
 
Input and output are often the performance bottleneck in a program. Reading from or writing to disk can be hundreds of times slower than reading from or writing to memory. Network connections and user input are even slower.
While disk capacities and speeds have increased over time, they have never kept pace with CPU speeds. Therefore, it's important to minimize the number of reads and writes a program actually does.
Most input stream classes have efficient polymorphic read() methods that read chunks of contiguous data into a byte array. This is faster than reading each element of the array separately.
To attempt to read 10 bytes from System.in, you could use the following code:
try {
  byte[] b = new byte[10];
  System.in.read(b);
}
catch (IOException e) {
  System.err.println("Couldn't read from System.in!");
}
Reads don't always succeed in getting as many bytes as you want.
Conversely, there's nothing to stop you from trying to read more data into the array than will fit.
If you do read more data than the array has space for, an ArrayIndexOutOfBoundsException will be thrown.
Byte Array Buffer - Exercise
Click the Exercise link below to write a program that uses a byte array buffer, an InputStream, and the System.out.println() method to copy data from System.in to System.out.
Byte Array Buffer - Exercise
  Course navigation