Streams

Back Up Next

 

Streams
An ordered sequence of data that have either a source (input stream) or destination (output stream)
Like C++'s cin and cout
Picture
Most I/O Stream classes in java.io do little more than read or write data in a particular manner (such as "I only read/write chars" or "I only read/write byte arrays" or "I buffer whatever bytes I read/write"), and they can be plugged together
Example

IOTest.java

import java.io.*;

public class IOTest {
	public static void main(String[] args) {
		try {
			File testFile = new File("C:\\DATA\\TEMP\\TestFile.txt");
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			FileWriter fw = new FileWriter(testFile);
			FileInputStream fis = new FileInputStream(testFile);
			DataOutputStream dos;

			String returnedLine = br.readLine();	//read a line from the console
			fw.write(returnedLine);			//write whatever was read into testFile
			fw.flush();
			fw.close();

			int ch;
			while ((ch = fis.read()) != -1)	//read in from file what we just wrote
				System.out.print((char)ch);

			fis.close();

			dos = new DataOutputStream(new FileOutputStream(testFile));
			dos.writeBoolean(true);			//write "true" to the file			dos.close();
		} catch (FileNotFoundException e) {
			System.out.println("File not found");
		} catch (IOException ee) {
			//consume IOExceptions for now
		}
	}
}