欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java實(shí)現(xiàn)追加內(nèi)容到文件末尾的常用方法分析

 更新時(shí)間:2017年10月07日 01:55:48   作者:王奎  
這篇文章主要介紹了java實(shí)現(xiàn)追加內(nèi)容到文件末尾的常用方法,結(jié)合具體實(shí)例分析了java文件流及寫入指針等相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了java實(shí)現(xiàn)追加內(nèi)容到文件末尾的常用方法。分享給大家供大家參考,具體如下:

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
public class WriteStreamAppend {
/**
* 追加文件:使用FileOutputStream,在構(gòu)造FileOutputStream時(shí),把第二個(gè)參數(shù)設(shè)為true
*
* @param fileName
* @param content
*/
public static void method1(String file, String conent) {
  BufferedWriter out = null;
  try {
     out = new BufferedWriter(new OutputStreamWriter(
         new FileOutputStream(file, true)));
         out.write(conent);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
}
/**
* 追加文件:使用FileWriter
*
* @param fileName
* @param content
*/
public static void method2(String fileName, String content) {
    try {
      // 打開一個(gè)寫文件器,構(gòu)造函數(shù)中的第二個(gè)參數(shù)true表示以追加形式寫文件
      FileWriter writer = new FileWriter(fileName, true);
      writer.write(content);
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
}
/**
* 追加文件:使用RandomAccessFile
*
* @param fileName
*      文件名
* @param content
*      追加的內(nèi)容
*/
public static void method3(String fileName, String content) {
    try {
      // 打開一個(gè)隨機(jī)訪問文件流,按讀寫方式
      RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
      // 文件長度,字節(jié)數(shù)
      long fileLength = randomFile.length();
      // 將寫文件指針移到文件尾。
      randomFile.seek(fileLength);
      randomFile.writeBytes(content);
      randomFile.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
}
public static void main(String[] args) {
    System.out.println("start");
    method1("c:/test.txt", "追加到文件的末尾");
    System.out.println("end");
}

更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java文件與目錄操作技巧匯總》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》和《Java緩存操作技巧匯總

希望本文所述對大家java程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論