Java将新文件的数据附加到旧文件

时间:2011-12-01 06:23:30

标签: java file-io

在第一步中创建一个文件说test1.txt并向其添加记录,其余记录到test2.txt。现在我想将test2.txt的记录追加到test1.txt。如何将它们附加到test1.txt。分割文件的原因是我有一个大约有53K记录的List,它无法写入单个文件,因为缓冲区写入器正在关闭它达到52K。 用于创建单个文件的函数是

    public void exportApprovedList() throws IOException {
    File approvedWhiteListFile = new File("/var/tmp/livecron/dictionary.common");
    BufferedWriter bw = new BufferedWriter(new FileWriter(approvedWhiteListFile));

    if (approvedWhiteListFile.exists()) {
        List<WhiteListTerm> approvedWhiteList = whiteListBO.getByStatus("APPROVED");
        for (WhiteListTerm whiteList : approvedWhiteList) {
            bw.write(whiteList.getTerm() + "|" + 
    whiteListCategoryBO.getById(whiteList.getCategoryId()).getCategoryname());
            bw.newLine();
        }
    }
    bw.close();
   }

1 个答案:

答案 0 :(得分:3)

试试这个......

import java.io. *; 公共类FileReadWrite {

public void writeFile(String sorcefile) 
{
     try{
          FileInputStream fis = new FileInputStream(sorcefile);
          DataInputStream dis = new DataInputStream(fis);
          BufferedReader br = new BufferedReader(new InputStreamReader(dis));
          FileWriter fw=new FileWriter("src/output.java",true);
          BufferedWriter bw=new BufferedWriter(fw);
          String strLine;
          //Read File Line By Line
          while ((strLine = br.readLine()) != null)   
          {
          System.out.println (strLine);
          bw.append(strLine);
          }           
          //Close the input stream
          br.close();
          dis.close();
          fis.close();
          fw.flush();
          bw.flush();
          fw.close();
          bw.close();             
            }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
          }
}

public static void main(String args [])   {      FileReadWrite frw = new FileReadWrite();      frw.writeFile(“巫文文件名称hfull路径”);   } }