Many Java programs are required to communicate with other systems or programs to get or send data. Java handles this communication through data streams.
Input streams send data from some external source to the Java program, and output streams send data from the Java program to an external area. The basic type of stream is referred to as a byte stream. Byte streams carry integers with values that range from 0 to 255. A derivation of the byte stream is the character stream. A character stream handles text data only and also supports Unicode.
Streams are fairly easy to use. You simply need to declare an object that is associated with the external system with which you want to communicate. You then use the methods associated with this class to read or write bytes, strings, and so on.
The following example shows a simple Java program that reads in a file from the user's computer and writes the contents back to the screen and to another file.
import java.io.*; public class Jsap1003 { public static void main (String[] args) { // Instantiate the File Class for our File names and streams File inFile, outFile; FileInputStream inStream = null; FileOutputStream outStream = null; int oneByte; boolean eof = false; boolean cool = false; // Open up the data files, catch the exception if we cannot // do this for some reason try { inFile = new File("testin.txt"); outFile = new File("testout.txt"); inStream = new FileInputStream(inFile); outStream = new FileOutputStream(outFile); cool = true; } catch (FileNotFoundException err) { System.err.println("Cannot open input file"); } catch (IOException err) { System.err.println("Cannot open output file"); } // If there are errors, just quit if (cool == false ) return; // Now read in the input file, write out to screen and write // out to the new file try { while(!eof) { oneByte = inStream.read(); if (oneByte == -1 ) { eof = true; } else { System.out.print((char)oneByte); outStream.write(oneByte); } } inStream.close(); outStream.close(); } catch (IOException err) { System.err.println("Error during read/write operation"); } } }
Team-Fly |