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, aFile
object, or aFileDescriptor
object. 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-1777FileStreamsTest
program creates aFileInputStream
from aFile
object with this code:Note the use of theFile inputFile = new File("farrago.txt"); FileInputStream fis = new FileInputStream(inputFile);File
object,inputFile
, in the constructor.inputFile
represents the named file,farrago.txt
, on the native file system. This program only usesinputFile
to create aFileInputStream
onfarrago.txt
. However, the program could useinputFile
to get information aboutfarrago.txt
such as its full path name.
Input and Output Streams |