java IO 输入输出(十)

十、添加内容到文件尾

    向文件尾追加内容有多种方法,下面介绍两种常用的方法。具体如下:
    1、通过RandomAccessFile以读写的方式打开文件输出流,使用它的seek方法可以将读写指针移到文件尾,再使用它的write方法将数据写道读写指针后面,完成文件追加。
    2、通过FileWriter打开文件输出流,构造FileWriter时指定写入模式,是一个布尔值,为true时表示写入的内容添加到已有文件内容的后面,为false时重新写文件,以前的数据被清空,默认为false。
   
实例演示

 

package  book.io;

import  java.io.FileWriter;
import  java.io.IOException;
import  java.io.RandomAccessFile;

/**
 * 将内容追加到文件的尾部
 * 
@author joe
 *
 
*/


public   class  AppendToFile  {
    
/**
     * A方法追加文件。使用RandomAccessFile
     * 
@param fileName    文件名
     * 
@param content    追加的内容
     
*/

    
public static void appendMethodA(String fileName, String content) {
        
try {
            
//按读写方式打开一个随机访问文件流
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            
long fileLength = randomFile.length();    //文件长度,字节数
            
//将写文件指针移到文件尾
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        }
 catch (IOException e) {
            e.printStackTrace();
        }

    }

    
    
/**
     * B方法追加文件。使用FileWriter
     * 
@param fileName    文件名
     * 
@param content    追加的内容
     
*/

    
public static void appendMethodB(String fileName, String content) {
        
try {
            
//打开一个写文件器,构造函数的第二个参数true表示以追加的形式写文件
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        }
 catch (IOException e) {
            e.printStackTrace();
        }

    }

    
    
public static void main(String[] args) {
        String fileName 
= "d:/work/temp/newTemp.txt";
        String content 
= "new append!";
        
//按方法A追加文件内容
        AppendToFile.appendMethodA(fileName, content);
        AppendToFile.appendMethodA(fileName, 
"append end.  ");
        ReadFromFile.readFileByLines(fileName);    
//显示文件内容
        
//按方法B追加文件内容
        AppendToFile.appendMethodB(fileName, content);
        AppendToFile.appendMethodB(fileName, 
"append end.  ");
        ReadFromFile.readFileByLines(fileName);    
//显示文件内容
        
    }


}

输出结果:
以行为单位读取文件内容,一次读取一整行:
line:1: 文件内容:
line:2: 1,The First line;
line:3: 2,The second line.new append!append end.
以行为单位读取文件内容,一次读取一整行:
line:1: 文件内容:
line:2: 1,The First line;
line:3: 2,The second line.new append!append end.
line:4: new append!append end.  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值