- import java.io.BufferedWriter;
- import java.io.FileOutputStream;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- import java.io.RandomAccessFile;
- /**
- * 描述:追加內(nèi)容到文件末尾
- * @author Administrator
- *
- */
- 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 {
- // 打開(kāi)一個(gè)寫(xiě)文件器,構(gòu)造函數(shù)中的第二個(gè)參數(shù)true表示以追加形式寫(xiě)文件
- 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 {
- // 打開(kāi)一個(gè)隨機(jī)訪問(wèn)文件流,按讀寫(xiě)方式
- RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
- // 文件長(zhǎng)度,字節(jié)數(shù)
- long fileLength = randomFile.length();
- // 將寫(xiě)文件指針移到文件尾。
- 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");
- }
- }
只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。 | ||
![]() |
||
網(wǎng)站導(dǎo)航:
博客園
IT新聞
Chat2DB
C++博客
博問(wèn)
管理
|
||
相關(guān)文章:
|
||