Java file read/write operations, java file read/write operations

Source: Internet
Author: User

Java file read/write operations, java file read/write operations

I. Reading files from Java

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

Encoding:

 1 File file = new File("D:/1.txt"); 2         FileReader fr = new FileReader(file); 3         BufferedReader bf = new BufferedReader(fr); 4         StringBuffer sbuffer = new StringBuffer(); 5         String temp = null; 6         while((temp = bf.readLine()) !=null){ 7             sbuffer.append(temp+"\n"); 8         } 9         System.out.println(sbuffer.toString());10         11         System.out.println();

Result:

Ii. Writing files

Case: The 1.txt file in the ddisk is written into a 2.txt file on the ddisk.

Encoding:

 1 File file = new File("D:/1.txt"); 2         FileReader fr = new FileReader(file); 3         BufferedReader bf = new BufferedReader(fr); 4         StringBuffer sbuffer = new StringBuffer(); 5         String temp = null; 6         while((temp = bf.readLine()) !=null){ 7             sbuffer.append(temp+"\n"); 8         } 9         System.out.println(sbuffer.toString());10         11         System.out.println();12         File outfile = new File("D:/2.txt");13         if(!outfile.exists()){14             try {15                 outfile.createNewFile();16             } catch (IOException e) {17                 // TODO Auto-generated catch block18                 e.printStackTrace();19             }20         }21         byte[] b = (sbuffer.toString()).getBytes();22         FileOutputStream fs = null;23         fs = new FileOutputStream(outfile);24         fs.write(b);25         26         fs.close();27         bf.close();    28     

 

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.