首頁  >  文章  >  Java  >  java寫入文件的幾種方法

java寫入文件的幾種方法

黄舟
黄舟原創
2016-12-12 13:20:401230瀏覽

一,FileWritter寫入檔案

FileWritter, 字元流寫入字元到檔案。預設情況下,它會使用新的內容取代所有現有的內容,然而,當指定一個true (布林)值作為FileWritter建構子的第二個參數,它會保留現有的內容,並追加新內容在檔案的末端。

1. 替換所有現有的內容與新的內容。

new FileWriter(file);2. 保留現有的內容和附加在該文件的末尾的新內容。

代码如下:
new FileWriter(file,true);

追加文件範例
一個文字文件,命名為“javaio-appendfile.txt”,並包含以下內容。

ABC Hello追加新內容new FileWriter(file,true)

代码如下:
package com.yiibai.file;

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class AppendToFileExample 
{
    public static void main( String[] args )
    { 
     try{
      String data = " This content will append to the end of the file";

      File file =new File("javaio-appendfile.txt");

      //if file doesnt exists, then create it
      if(!file.exists()){
       file.createNewFile();
      }

      //true = append file
      FileWriter fileWritter = new FileWriter(file.getName(),true);
             BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
             bufferWritter.write(data);
             bufferWritter.close();

         System.out.println("Done");

     }catch(IOException e){
      e.printStackTrace();
     }
    }
}

結果
現在,文字檔案「javaio-appendfile.txt」內容更新如下:

ABC Hello This content will append totxt」內容更新如下:

ABC Hello This content will append totxt the endo
二,BufferedWriter寫入檔案

緩衝字元(BufferedWriter )是一個字元流類別來處理字元資料。不同於位元組流(資料轉換成位元組),你可以直接寫字串,數組或字元資料保存到檔案。

代码如下:
package com.yiibai.iofile;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
 public static void main(String[] args) {
  try {

   String content = "This is the content to write into file";

   File file = new File("/users/mkyong/filename.txt");

   // if file doesnt exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }

   FileWriter fw = new FileWriter(file.getAbsoluteFile());
   BufferedWriter bw = new BufferedWriter(fw);
   bw.write(content);
   bw.close();

   System.out.println("Done");

  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn