FileReader和 FileWriter 读写字符串
1 package object.io; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileReader; 6 import java.io.FileWriter; 7 import java.io.IOException; 8 9 public class FileWrite { 10 11 public static void main(String[] args) throws IOException { 12 // TODO Auto-generated method stub 13 FileReader reader=new FileReader("D:\\Program Files (x86)\\io\\fileWriter.txt"); 14 BufferedReader bReader=new BufferedReader(reader); 15 FileWriter writer=new FileWriter("D:\\Program Files (x86)\\io\\fileWriter2.txt"); 16 BufferedWriter bWriter=new BufferedWriter(writer); 17 String content=""; 18 //readLine一行一行的读取 19 while((content=bReader.readLine())!=null){ 20 //\r\n换行 21 bWriter.write(content+"\r\n"); 22 } 23 /** 24 * 关闭流的顺序: 25 * 当A依赖B的时候先关闭A,再关闭B 26 * 带缓冲的流最后关闭的时候会执行一次flush 27 */ 28 reader.close(); 29 bReader.close(); 30 bWriter.close(); 31 writer.close(); 32 33 } 34 35 }
操作结果:
练习:
1 package object.io; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileNotFoundException; 6 import java.io.FileReader; 7 import java.io.FileWriter; 8 import java.io.IOException; 9 10 public class FileWrite2 { 11 12 public static void main(String[] args) throws IOException { 13 // TODO Auto-generated method stub 14 FileReader reader=new FileReader("D:\\Program Files (x86)\\io\\fileWriter11.txt"); 15 BufferedReader bReader=new BufferedReader(reader); 16 FileWriter writer=new FileWriter("D:\\Program Files (x86)\\io\\fileWriter22.txt"); 17 BufferedWriter bWriter=new BufferedWriter(writer); 18 String content=""; 19 while((content=bReader.readLine())!=null){ 20 if(content.contains("{title}")){ 21 content=content.replace("{title}", "放假"); 22 } 23 if(content.contains("{description}")){ 24 content=content.replace("{description}", "元旦放假三天"); 25 } 26 bWriter.write(content+"\r\n"); 27 } 28 /** 29 * 关闭流的顺序: 30 * 当A依赖B的时候先关闭A,再关闭B 31 * 带缓冲的流最后关闭的时候会执行一次flush 32 */ 33 reader.close(); 34 bReader.close(); 35 bWriter.close(); 36 writer.close(); 37 38 } 39 40 }
结果:
原文地址:https://www.cnblogs.com/ztt0918/p/8117120.html
时间: 2024-10-10 22:09:47