Session 10 |
Streams
Java programs perform almost all I/O using streams. Streams are a smart way to deal with input/output without having every part of our code understand the difference between a keyboard and a network, for example.
The streams can be divided into two: the input streams and the output streams. Each of them has its own abstract class: InputStream
and OutputStream
.
These classes can read and write only bytes (reading/writing other data types like integers, doubles, text will be discussed later)!
To open an input/output stream, use the following statements:
InputStream myInput = new FileInputStream("myPicture.jpg"); OutputStream myOutput = new FileOutputStream("mySecondPicture.jpg");
Keep track of the following important methods of the abstract classes:
InputStream
int read()
- reads and returns the next byte of data from the input stream;int read(byte[] buf)
- reads 1 <= n <= buf.length bytes from the input stream and stores them into the buffer array;void close()
- closes the input stream and releases any system resources associated with the stream.
OutputStream
void write(int b)
- writes the specified byte to the output stream;void write(byte[] buf, int offset, int length)
- writes length bytes from the specified byte array buf starting at offset offset to the output stream;void close()
- closes the output stream and releases any system resources associated with this stream.
The following example demonstrates manipulations with streams. Namely, the program makes a copy of the file. The method myCopy
reads bytes from the input stream and places each byte into the output stream. (Note that reading byte by byte is not efficient; therefore, the number of the bytes read at a time is increased to 1024).
//This program makes a copy of the given file: import java.io.*; public class CopyMyFile { private static void myCopy(String myFile, String myCopy) throws Exception { InputStream myInput = new FileInputStream(myFile); OutputStream myOutput = new FileOutputStream(myCopy); byte[] myBuffer = new byte[1024]; int myRead = myInput.read(myBuffer); while (myRead > 0) { myOutput.write(myBuffer, 0, myRead); // only the part that has data myRead = myInput.read(myBuffer); // read the next 1024 bytes } myInput.close(); myOutput.close(); } public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Have you entered a file name?"); System.exit(1); } myCopy(args[0], args[0] + ".copy"); } }
If you use IntelliJ, add the program arguments as follows: Run
-> Edit Configurations
-> Configuration
tab -> Program arguments
.
Why can't we make a copy of the whole file at once? The problem is connected to the file size. If the file is too large, the RAM will get full during the reading. Reading the file by portions eliminates the problem of the memory overflow.
Session 10 |