Java stringbuffer read-write files

Source: Internet
Author: User

StringBuffer Read and write files

import java.io.;
public class FileIO_StringBuffer {
public static void main(String[] args) {
//读文件到Stringbuffer
StringBuffer sb = new StringBuffer();
String sourcePath = "C:\Users\Administrator\Desktop\1.txt";//源文件路径(
.*)
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(sourcePath));
String str;
while((str = br.readLine()) != null) {//逐行读取
sb.append(str);//加在StringBuffer尾
sb.append("\r\n");//行尾 加换行符
}
br.close();//别忘记,切记
}
catch(Exception e){
System.out.println(e.getMessage());
}
//写入文件
String targetPath = "C:\Users\Administrator\Desktop\2.txt";//目标文件路径
File f = new File(targetPath);//新建文件
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(sb.toString());
bw.flush();
bw.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}

Java stringbuffer read-write files

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.