IO stream Common Errors and io Common Errors

Source: Internet
Author: User

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

}

    

    

    

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.