I/O in Java (2)
1. Reading and Writing large files
// Step 1: import the class;
// 1G = 1024*1024*1024
Import java. io .*;
Class Test {
Public static void main (String args []) {
// Declare the input stream application
FileInputStream FCM = null;
// Declare the reference of the output stream
FileOutputStream fos = null;
Try {
// Declare the object of the input stream
FCM = new FileInputStream ("e:/src/from.txt ");
// Declaration indicates the object of the output stream
Fos = new FileOutputStream ("e:/src/to.txt ");
// Generate a byte array
Byte [] buffer = new byte [1024];
While (){
// Call the read method of the input stream object to read data
Int temp = FCM. read (buffer, 0, buffer. length );
If (temp =-1 ){
Break;
}
Fos. write (buffer, 0, temp );
}
}
Catch (Exception e ){
System. out. println (e );
}
Finally {
Try {
FCM. close ();
Fos. close ();
}
Catch (Exception e ){
System. out. println (e );
}
}
}
}
2. How to Use the livestream
// Delimiter stream: When a file is read and written, it is based on characters.
// Byte input stream: Reader <------ FileReader
// In read (char [], int off, int len)
// Byte output stream: Writer <------ FileWriter
// Void write (char [], int off, int len)
// Read and write abcde
Import java. io .*;
Public class TestChar {
Public static void main (String arg []) {
FileReader fr = null;
FileWriter fe = null;
Try {
Fr = new FileReader ("e:/src/from.txt ");
Fe = new FileWriter ("e:/src/to.txt ");
Char [] buffer = new char [100];
Int temp = fr. read (buffer, 0, buffer. lenfth );
Fw. write (buffer, 0, temp );
}
Catch (Exception e ){
System. out. println (e );
}
Finally {
Try {
Fr. close ();
Fe. close ();
}
Catch (Exception e ){
System. out. println (e );
}
}
}
}