Java file operation read and write operations

Source: Internet
Author: User

One, Java read file

Case 1: Read the 1.txt file of the D drive

Coding:

1File File =NewFile ("D:/1.txt");2FileReader FR =Newfilereader (file);3BufferedReader BF =NewBufferedReader (FR);4StringBuffer Sbuffer =NewStringBuffer ();5String temp =NULL;6          while(temp = Bf.readline ())! =NULL){7Sbuffer.append (temp+ "\ n");8         }9 System.out.println (sbuffer.tostring ());Ten          OneSystem.out.println ();

Results:

Second, write the file

Case: The 1.txt file content in D disk is written to a 2.txt file in D disk.

Coding:

1File File =NewFile ("D:/1.txt");2FileReader FR =Newfilereader (file);3BufferedReader BF =NewBufferedReader (FR);4StringBuffer Sbuffer =NewStringBuffer ();5String temp =NULL;6          while(temp = Bf.readline ())! =NULL){7Sbuffer.append (temp+ "\ n");8         }9 System.out.println (sbuffer.tostring ());Ten          One System.out.println (); AFile outfile =NewFile ("D:/2.txt"); -         if(!outfile.exists ()) { -             Try { the outfile.createnewfile (); -}Catch(IOException e) { -                 //TODO auto-generated Catch block - e.printstacktrace (); +             } -         } +         byte[] B =(Sbuffer.tostring ()). GetBytes (); AFileOutputStream fs =NULL; atFS =NewFileOutputStream (outfile); - Fs.write (b); -          - fs.close (); - Bf.close ();  -     

Java file operation read and write operations

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.