今天是本人第一天加入CSDN程序猿大军,咬了咬牙决定坚持更新个博客。今天所遇到的问题是:文件输出流的覆盖问题
简而言之就是在输出文件流时由于循环的存在,使得文件不断被重写,因而生成的文件只有一条记录。
解决办法
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
public class xxx {
static java.io.File file = new java.io.File("/Users/apple/Documents/urls.txt");
public static void xx(String a, String b) throws Exception{
OutputStream os = null;//定义字节流
OutputStreamWriter osw = null;//OutputStreamWriter是字节流通向字符流的桥梁。
BufferedWriter bw = null;//定义缓冲区
//output the index#, title, pdfURL and the url of the publisher's for this document.
//if((matchedOne != null) && (Parsers.getArticlePDF(matchedOne)!= null))
try{
//从文件系统中的某个文件中获取字节
os = new FileOutputStream(file, true); //true是append设为允许,即可以在原文件末端追加。
//将字节流转换成字符流
osw = new OutputStreamWriter(os);
//把接收到的字符流放入缓冲区,提高读写速度。
bw = new BufferedWriter(osw);
bw.newLine();
//将字符串以流的形式写入文件
if((matchedOne != null))
bw.write(indexNum + "\t" + Parsers.getArticlePDF(matchedOne) + "\t" + Parsers.getArticleLink(matchedOne) + "\t" + title + "\t" + StringHandler.removeNonLetters(Parsers.getArticleName(matchedOne)).toLowerCase());
}catch(FileNotFoundException e){
System.out.println("找不到指定文件");
}catch(IOException e){
System.out.println("写入文件错误");
}finally{
bw.close();
osw.close();
os.close();
}
}