|
||
| Lesson 4
Objective
|
Counting the available bytes
Write program that uses byte array buffer/ available() method |
|
|
Write a program that uses a byte array buffer and the available() method to efficiently copy data from System.in to System.out.
It's sometimes convenient to know how many bytes are available to be read before you attempt to read them. The InputStream class's available() method tells you how many bytes you can read without blocking. public int available() throws IOException try { byte[] b = new byte[100]; int offset = 0; while (offset < b.length) { int a = System.in.available(); int bytesRead = System.in.read(b, offset, a); if (bytesRead == -1) break; // end-of-stream offset += bytesRead; } } catch (IOException e) { System.err.println("Couldn't read from System.in!"); }
There's a potential bug in the above code. There may be more bytes available than there is space in the array to hold them. One common idiom is
to size the array according to the number that available() returns, like this:
try { byte[] b = new byte[System.in.available()]; System.in.read(b); } catch (IOException e) { System.err.println("Couldn't read from System.in!"); } When no bytes are available to be read, available() returns 0. Available Bytes - Exercise
Click the Exercise link below to write a program that uses
Available Bytes - Exercise |
||
|
|
||
