Java往文件追加内容


package com.tij.io.file;

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.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * 追加内容到文件中
 * @author GYJ
 * @date 2014-3-22
 */
public class AppendFile {

  /**
   * 之前写了如何写入文件,单是写入文件是覆盖了之前的内容
   * <p>这个实例展现如何追加内容到文件中
   * @param args
   * @throws IOException 
   */
  public static void main(String[] args) throws IOException {
    //追加的目标文件
    String fileName = "/Users/GYJ/java1.txt";
    //追加的数据
    String appendData = "this string will be append to last row fileName";
    //追加文件
    addpendUsingOutputStream(fileName, appendData);
    appendUsingBufferedWrite(fileName, appendData, 400);
    appendUsingFileWrite(fileName, appendData);
    //读出文件
    File file = new File(fileName);
    FileInputStream fis = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(fis, Charset.defaultCharset());
    BufferedReader br = new BufferedReader(isr);
    String line;
    int i = 0;
    while ((line = br.readLine()) != null) {
      i ++;
      System.out.println(i + "read result = " + line);
    }
    br.close();
  }
  
  /**
   * 使用普通流
   * @param fileNme	被追加的文件名称
   * @param data		被追加的数据内容
   * @throws IOException 
   */
  private static void addpendUsingOutputStream(String fileName, String data) throws IOException {
    //true: 表示是追加的标志
    FileOutputStream os = new FileOutputStream(new File(fileName), true);
    os.write(data.getBytes(), 0, data.length());
    os.close();
  }
  
  /**
   * 使用BufferedWrite
   * @param fileName
   * @param data
   * @throws IOException 
   */
  private static void appendUsingBufferedWrite(String fileName, String data, int noOfLines) throws IOException {
    File file = new File(fileName);
    FileWriter fw = null;
    BufferedWriter bw = null;
    //true:表示是追加的标志
    fw = new FileWriter(file, true);
    bw = new BufferedWriter(fw);
    //开始输出写入文件
    for (int i = 0; i < noOfLines; i++) {
      bw.newLine();
      fw.write(data);
    }
    bw.close();
    fw.close();
  }
  
  /**
   * 使用fileWrite
   * @param fileName
   * @param data
   * @throws IOException 
   */
  private static void appendUsingFileWrite(String fileName, String data) throws IOException {
    File file = new File(fileName);
    FileWriter fw = null;
    //true:表示是追加的标志
    fw = new FileWriter(file, true);
    fw.write(data);
    fw.close();
  }

}




  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值