当前位置: 移动技术网 > IT编程>开发语言>Java > java在文件尾部追加内容的简单实例

java在文件尾部追加内容的简单实例

2019年07月22日  | 移动技术网IT编程  | 我要评论

十年后最富24个城市,ued黑庄,合生元米粉最新事件

如下所示:

import java.io.filewriter;
import java.io.ioexception;
import java.io.randomaccessfile;

/**
 * 将内容追加到文件尾部.
 * @author haicheng.cao
 *
 */
public class appendtofile {
  /**
   * a方法追加文件:使用randomaccessfile
   */
  public static void appendmethoda(string filename, string content) {
    try {
      // 打开一个随机访问文件流,按读写方式
      randomaccessfile randomfile = new randomaccessfile(filename, "rw");
      // 文件长度,字节数
      long filelength = randomfile.length();
      //将写文件指针移到文件尾。
      randomfile.seek(filelength);
      randomfile.writebytes(content);
      randomfile.close();
    } catch (ioexception e) {
      e.printstacktrace();
    }
  }

  /**
   * b方法追加文件:使用filewriter
   */
  public static void appendmethodb(string filename, string content) {
    try {
      //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
      filewriter writer = new filewriter(filename, true);
      writer.write(content);
      writer.close();
    } catch (ioexception e) {
      e.printstacktrace();
    }
  }

  public static void main(string[] args) {
    string filename = "c:/temp/newtemp.txt";
    string content = "new append!";
    //按方法a追加文件
    appendtofile.appendmethoda(filename, content);
    appendtofile.appendmethoda(filename, "append end. \n");
    //显示文件内容
    readfromfile.readfilebylines(filename);
    //按方法b追加文件
    appendtofile.appendmethodb(filename, content);
    appendtofile.appendmethodb(filename, "append end. \n");
    //显示文件内容
    readfromfile.readfilebylines(filename);
  }
}

以上这篇java在文件尾部追加内容的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网