Posted on 2009-07-14 23:52
Gavin.lee 阅读(644)
评论(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);

}

}
