|
|
Input and Output Streams |
File streams are perhaps the easist streams to understand. Simply put,FileInputStream(
FileOutputStream) 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 two file streams to copy the contents of one file into another:
Here are 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:TheSo 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-1777FileStreamsTestprogram creates aFileInputStreamfrom aFileobject with this code:Note the use of theFile inputFile = new File("farrago.txt"); FileInputStream fis = new FileInputStream(inputFile);Fileobject,inputFile, in the constructor.inputFilerepresents the named file,farrago.txt, on the native file system. This program only usesinputFileto create aFileInputStreamonfarrago.txt. However, the program could useinputFileto get information aboutfarrago.txtsuch as its full path name.
|
|
Input and Output Streams |