(Java讀寫TXT) 2萬多行的TXT分解成多個1000行的文件

原本一個很簡單的程序,腦袋真笨了一會...唉...寫了2個多小時...最後冷靜了一下用集合存放,才迎刃而解....發表一下做個紀念吧..

 

/**
 * 將一個txt文檔,分爲幾個文檔。
 * 
 * @author XiongXing
 *
 */
public class ReadAndWriteTxt {

 public static void main(String[] args) {
  try {
   readTxt();
  } catch (IOException e) {
   System.out.println("異常");
  }
  System.out.println("完畢");
 }
 public static void readTxt() throws IOException {
  int count =1;
  FileInputStream inputFile = new FileInputStream("F:/20110930/20110930.txt");
  String line = ""; // 用來保存每行讀取的內容
  BufferedReader reader = new BufferedReader(new InputStreamReader(inputFile));
  ArrayList<String> list=new ArrayList<String>();
  line = reader.readLine(); // 讀取第一行
  while (line != null) {
   list.add(line); // 將讀到的內容添加到 集合當中。

   if(count%1000==0){  //每一千行創建一個txt文件
    //FileOutputStream fos = new FileOutputStream("F:/20111001/"+count+".txt");
    PrintWriter pw=new PrintWriter(new OutputStreamWriter(new FileOutputStream("F:/20111001/"+count+".txt")));
    for(Iterator<String> it=list.iterator();it.hasNext();){
     pw.println(it.next().toString());
    }
    pw.flush();
    pw.close();
    list.clear();
   }
   line = reader.readLine(); // 讀取下一行
   count++;
  }
  //將最後多的幾行寫完
  PrintWriter pw=new PrintWriter(new OutputStreamWriter(new FileOutputStream("F:/20111001/end.txt")));
  for(Iterator<String> it=list.iterator();it.hasNext();){
   pw.println(it.next().toString());
  }
  pw.flush();
  pw.close();
  list.clear();
  reader.close();
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章