IO stream Common Errors and io Common Errors
Requirement: use an IO stream to copy the content of a file to another file.
The file "good boy.txt" is located in the root directory of drive D. Copy the content of this file to c: \ myFile.txt.
Code:
Import java. io .*;
Public classInputAndOutputFile {
Public static void main (String [] args ){
FileInputStream FCM = null;
FileOutPutStream fos = null;
Try {// 1. Create an input stream object and read the D:/good boy.txt File
FCM = new FileInputStream ("D:/good boy.txt ");
// 2. Create an output stream object
Fos = new FileOutputStream ("C:/myFile.txt", true );
// 3. Create a transfer station array to store the content read each time
Byte [] words = new byte [1024];
// 4. Implement File Read and Write Through Loop
Inte len =-1;
While (len = FS. read (words ))! =-1 ){
Fos. write (words, 0, len );
}
// 5 forcibly clear the buffer
Fos. flush ();
System. out. println ("the copy is complete. Please check the file! ");
} Catch (FileNotFoundExcepton e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
// 6. Close the stream
Try {
FCM. close ();
Fos. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
Errors often occur when while LOOP writing:
Error code:
While (FCM. read ())! =-1) {// The error is here: At this time, the first read/write has been implemented for the FIPs. read (); so the characters cached in words are less than the first one, leading to a result error.
FS. read (words); // read the file
Fos. write (words, 0, words. length); // write a file
}