FileInputStream/FileOutputStream throughout this
lecture but you should konw how to use FileReader/FileWriter as
well. The classes has similar API.
| Constructors/Methods | Description |
|---|---|
|
FileInputStream(String name) throws FileNotFoundException FileInputStream(File file) throws FileNotFoundException |
Creates a FileInputStream by opening a connection to an actual file.If the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown.
|
| int read() throws IOException | Read and return the next byte of data, or -1 if the end of the file is reached. |
int read(byte[] b) throws IOException int read(byte[] b, int off, int len) throws IOException |
Reads up to b.length/len bytes of data from this input stream into
an array of bytes.It returns the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached. |
| int available() throws IOException | Returns the number of bytes that can be read from this file input stream without blocking |
| long skip(long n) throws IOException | Skips over and discards n bytes of data from the input stream. |
| void close() throws IOException | Closes this file input stream and releases any system resources associated with the stream. |
| Constructors/Methods | Description |
|---|---|
|
FileOutputStream(File file) throws FileNotFoundException FileOutputStream(String name) throws FileNotFoundException FileOutputStream(String name, boolean append) throws FileNotFoundException |
Creates an output file stream to write to the file with the specified file or
name. If append is true, then bytes will be written to the end of the file
rather than the beginning.If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.
|
|
void write(int b)throws IOException void write(byte[] b) throws IOException void write(byte[] b, int off, int len) throws IOException |
Writes the specified byte(s) to this file output stream. |
| void close() throws IOException | Closes this file output stream and releases any system resources associated with this stream. This file output stream may no longer be used for writing bytes. |
IOExceptionFileNotFoundException : a subclass of IOException. import java.io.*; public class ExceptionTest { public static void main(String[] args) { FileOutputStream out = null; try { out = new FileOutputStream("test"); out.write('A'); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException"); } catch (IOException ex) { System.out.println("IOException"); } finally { if(out != null) { try { out.close(); } catch (IOException ex) { } } } } }Incorrect version (compiling error)
import java.io.*; public class ExceptionTest { public static void main(String[] args) { FileOutputStream out = null; try { out = new FileOutputStream("test"); out.write('A'); } catch (IOException ex) { System.out.println("IOException"); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException"); } finally { if(out != null) { try { out.close(); } catch (IOException ex) { } } } } }
FileInputStream and FileOutputStream
to copy the contents of a file named farrago.txt into a file called
outagain.txt.
import java.io.*;
public class CopyBytes {
public static void main(String[] args) throws IOException {
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");
FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}
This program is very simple.
It opens a FileInputStream on farrago.txt and
opens a FileOutputStream on outagain.txt.
The program reads bytes from
the inputstream as long as there's more input in the input
file and writes those bytes to the writer.
When the input runs out,
the program closes both the inputstream and the output stream.
Here is the code that the CopyByte program uses
to create a file:
File inputFile = new File("farrago.txt");
FileReader in = new FileReader(inputFile);
This code creates a File object that represents the named
file on the native file system. File is a utility class
provided by java.io. The CopyByte program uses this object only to
construct a file reader on a file.
However, the program could use inputFile to get information, such as its full path name, about the file.
After you've run the program, you should find an exact copy of
farrago.txt in a file named outagain.txt in
the same directory. Here is the content of the file:
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-1777
CopyFile.java such that
java CopyFile file1 file2 copy file1 to
file2. A warning message is given when file2
exists.import java.io.*; public class CopyFile { public static void main(String[] args) throws IOException { String copyFromFileName = null; String copyToFileName = null; FileInputStream fileIn = null; FileOutputStream fileOut = null; if(args.length < 2) { usage(); return; } else { copyFromFileName = args[0]; copyToFileName = args[1]; try { fileIn = new FileInputStream(copyFromFileName); } catch (FileNotFoundException ex) { System.out.println("File " + copyFromFileName + "not found"); return; } if(new File(copyToFileName).exists()) { System.out.println("File " + copyToFileName + " exists."); fileIn.close(); return; } try { fileOut = new FileOutputStream(copyToFileName); } catch (FileNotFoundException ex) { System.out.println("File " + copyToFileName + "cannot be created"); fileIn.close(); return; } } int c; while((c = fileIn.read()) != -1) { fileOut.write(c); } fileIn.close(); fileOut.close(); } private static void usage() { System.out.println("Usage : CopyFrom filenameIn filenameOut"); } }
copy1 takes 20540 ms to finish the job. copy2 just takes 770 ms to finish it. import java.io.*; public class FilePerformance { public static void copy1(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); int ch; while((ch = in.read())!= -1) { out.write(ch); } in.close(); out.close(); } public static void copy2(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); int length = 32; // 32 is a power of 2. // use a power of 2 can increase the performance byte[] ch = new byte[length]; while((length = in.read(ch))!= -1) { out.write(ch,0,length); } in.close(); out.close(); } public static void main(String[] args) throws IOException { File from = new File("pic.jpg"); File to = new File("pic2.jpg"); long start = System.currentTimeMillis(); for(int i = 0; i < 10; i++) { System.out.println(i); copy1(from, to); } long end = System.currentTimeMillis(); System.out.println("Time : " + (end - start) + "ms." ); start = System.currentTimeMillis(); for(int i = 0; i < 10; i++) { System.out.println(i); copy2(from, to); } end = System.currentTimeMillis(); System.out.println("Time : " + (end - start) + "ms." ); } }