java流读取txt文件并写入另一个txt文件



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
//import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


public class StreamTest {


public static void main(String[] args) throws Exception {
//读取a.txt
File pathFile = new File("a.txt");//可使用绝对或相对路径
if(pathFile.isFile() && pathFile.exists()){
FileInputStream is = new FileInputStream(pathFile);
InputStreamReader isReader = new InputStreamReader(is,"utf-8");
BufferedReader br = new BufferedReader(isReader);
// BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(pathFile),"utf-8"));
File writeFl = new File("b.txt");
if( !writeFl.exists()){//不存在则创建
writeFl.createNewFile();//创建新文件
}
FileOutputStream fs = new FileOutputStream(writeFl,true);//true设置为追加内容 默认false;
OutputStreamWriter ow = new OutputStreamWriter(fs,"utf-8");
BufferedWriter bw= new BufferedWriter(ow);
// BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writeFl,true)));

StringBuffer nb = new StringBuffer();
String lineTxt = null;
while((lineTxt=br.readLine())!=null){
StringBuffer sb = new StringBuffer();
sb.append(lineTxt + "\n");//"\n"读取换行
//写入
bw.write(sb.toString()+"\r\n");//"\r\n" 写入换行
}
System.out.println(nb.toString());



isReader.close();
br.close();
bw.flush();
bw.close();

}else{
throw new Exception("文件不存在");
}


}


}

你可能感兴趣的:(二进制流,读取写入文件,java,file,stream,exception,txt)