BufferedWriter与BufferedRead --------------------------Test

时间:2024-08-02 08:34:32
 package com.test;

 import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* 将文档中每一行的男转为女,需要注意要读取的文件的编码格式与java文件的编码格式相同
* @author Administrator
*
*/
public class Demo2 { public static void main(String[] args) {
// TODO Auto-generated method stub Read read = new Read();
read.readWrite();
} } class Read {
public static void readWrite() { BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
//找到要进行转换的文件
File file = new File("D://userMsg//userinfo.txt");
//建立读取数据通道
FileReader fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String str = null;
//保存读取道德内容 输入流
List<String> list = new ArrayList<String>();
while ((str = bufferedReader.readLine()) != null) {
//进行男女转换
System.out.println(str);
String s = str.replaceAll("男", "女");
list.add(s);
}
//建立写入数据通道 输出流
FileWriter fileWriter = new FileWriter(file);
bufferedWriter = new BufferedWriter(fileWriter);
//遍历集合
for (String s : list) {
bufferedWriter.write(s);
System.out.println(s);
}
//流冲刷,如果缺少,可能导致写入不成功
bufferedWriter.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} }
}

BufferedWriter与BufferedRead  --------------------------Test


相关文章