Posted on 2009-07-14 23:52
Gavin.lee 閱讀(646)
評論(0) 編輯 收藏 所屬分類:
Log && File Operate
package com.Gavin.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;


/** *//**
* **********************************************
*
* @description 在文件后追加內容
* @author Gavin.lee
* @date Jul 14, 2009 3:25:58 PM
* @version 1.0 **********************************************
*/

public class FileAdd
{


/** *//**
* public FileOutputStream(String fileName,
boolean append)
throws FileNotFoundException
*/

public void fileAdd(String absolutePath, String content, boolean isAdd)
{

if(content == null)
{
return;
}

try
{
FileOutputStream fos = new FileOutputStream(new File(absolutePath), isAdd);
fos.write(content.getBytes());
fos.close();

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

/** *//**
* public FileWriter(String fileName,
boolean append)
throws IOException
*/

public void fileAdd2(String absolutePath, String content, boolean isAdd)
{

try
{
FileWriter fw = new FileWriter(absolutePath, isAdd);
PrintWriter pw = new PrintWriter(fw);
pw.println(content);
pw.close () ;
fw.close () ;

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

/** *//**
* public RandomAccessFile(File file,
String mode)
throws FileNotFoundException
含意 值
"r" 以只讀方式打開。調用結果對象的任何 write 方法都將導致拋出 IOException。
"rw" 打開以便讀取和寫入。如果該文件尚不存在,則嘗試創建該文件。
"rws" 打開以便讀取和寫入,對于 "rw",還要求對文件的內容或元數據的每個更新都同步寫入到底層存儲設備。
"rwd" 打開以便讀取和寫入,對于 "rw",還要求對文件內容的每個更新都同步寫入到底層存儲設備。

*/

public void fileAdd3(String absolutePath, String content, String mode)
{

try
{
RandomAccessFile rf = new RandomAccessFile(absolutePath, mode);
rf.seek(rf.length()); //將指針移動到文件末尾
rf.writeBytes(content);
rf.close();//關閉文件流

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

public static void main(String[] args)
{
FileAdd fa = new FileAdd();
fa.fileAdd("d:\\abc.txt", "test content", true);

}

}
