Input and Output Streams |
File streams are perhaps the easist streams to understand. Simply put, FileInputStream) represents an input (output) stream on a file that lives on the native file system. You can create a file stream from the filename, a Fileobject, or a FileDescriptorobject. Use file streams to read data from or write data to files on the file system.This small example uses the file streams to copy the contents of one file into another:
Here's the contents of the input fileimport java.io.*; class FileStreamsTest { public static void main(String[] args) { try { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); int c; while ((c = fis.read()) != -1) { fos.write(c); } fis.close(); fos.close(); } catch (FileNotFoundException e) { System.err.println("FileStreamsTest: " + e); } catch (IOException e) { System.err.println("FileStreamsTest: " + e); } } }farrago.txt
:The FileStreamsTest program creates a FileInputStream from a File object with this code:So she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a great she-bear, coming up the street, pops its head into the shop. 'What! no soap?' So he died, and she very imprudently married the barber; and there were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum himself, with the little round button at top, and they all fell to playing the game of catch as catch can, till the gun powder ran out at the heels of their boots. Samuel Foote 1720-1777Note the use of the File object,File inputFile = new File("farrago.txt"); FileInputStream fis = new FileInputStream(inputFile);inputFile
, in the constructor.inputFile
represents the named file,farrago.txt
, on the native file system. This program only usesinputFile
to create a FileInputStream onfarrago.txt
. However, the program could useinputFile
to get information aboutfarrago.txt
such as its full path name.See Also
java.io.FileInputStream
java.io.FileOutputStream
Input and Output Streams |