如何在文件末尾写入新数据,适用JavaNIO

在对文件进行写入操作时,我们经常会碰到的一个棘手的问题可能是:如何在一个已经有内容的文件末尾写入新数据而不覆盖掉原来的内容?现在本人介绍以下四种方法:

首先,假设在程序的当前目录中有一个文件“data.txt”,该文件中已经有内容,现在要进行的操作是在data.txt文件末尾定放字符串"Write in the end".

法一:

在FileOutputStream 或者 FileWriter 的构造器中加个参数 “true”,就如:

FileOutputStream fos = new FileOutputStream("data.txt",true);
//加个参数true表示在文件末尾写入,不加或者加上false表示在文件开头处定入
fos.write("Write in the end".getBytes());//用write(byte[] b)写入字符串
fos.close();//记得关闭文件流

或者可以用FileWriter


FileWriter fos = new FileWriter("data.txt",true); //同样加个参数true
fos.write("Write in the end");//该类有不同于FileOutputStream的write(String s)
fos.close();


法二:

利用java.nio.channel包里面的FileChannel类,该类有个position(long newPosition),参数newPosition表示“计算从文件开始的字节数 ”该方法的功能就是把指针位置设置在文件的newPosition处,而文件的末尾我们可以用FileChannel.size()来得到!也就是我们用position(FileChannel.size())
就可以把指针指向末尾,从而写入新数据,就如:



FileChannel fc = new RandomAccessFile("data.txt", "rw").getChannel(); // rw模式
//必须用RandomAccessFile("data.txt", "rw").getChannel();
//而不能用FileOutputStream.getChannel
fc.position(fc.size()); // //把指针移到文件末尾
fc.write(ByteBuffer.wrap("Write in the end ".getBytes())); //写入新数据
fc.close()
//如果我们硬是要用FileOutputStream.getChannel,可以写成:
FileChannel fc = new FileOutputStream("data.txt", true).getChannel(); //参数true也必须加上
fc.position(fc.size());
fc.write(ByteBuffer.wrap("Write in the end ".getBytes()));
fc.close();


法三:

用RandomAccess类的seek(long pos)代替方法二的position(long newPosition),不多讲,看例题:

RandomAccessFile rf = new RandomAccessFile("data.txt", "rw");
rf.seek(rf.length()); //length()方法,而不是上面的size()
rf.writeChars("Write in the end"); //wiriteChars写入字符串,写入的字符串中的每个字符在文件中都是占两个字节,比如write在文件中看到的是 w r i t e 。

法四:

利用FileChannel的 map(FileChannel.MapMode mode,long position,long size)方法创建一个MappedByteBuffer(内存映射文件),但是可“读/写”的MappedByteBuffer必须通过RandomAccessFile.getChannel.map()来创建,因为FileChannel.MapMode(文件映射模式的类型)只有三种:
1,MapMode.READ_ONLY 只读
2,MapMode.READ_WRITE 读/写
3,MapMode.PRIVATE 专用
而我们要在文件末尾写入的话就必须有到“写文件”,也就是要用到MapMode.READ_WRITE ,如果我们用FileInputStream或者FileOutputStream来获取通道的话都是“只读”或者“只写”,就没办法与MapMode.READ_WRITE 搭配起来,所以我们只能通过RandomAccessFile的"rw"模式来与MapMode.READ_WRITE搭配。
map方法中的参数:
1.mode :根据是按只读、读取/写入或专用(写入时拷贝)来映射文件,分别为 2.FileChannel.MapMode 类 中所定义的 READ_ONLY、READ_WRITE 或 PRIVATE 之一
3.position : 文件中的位置,映射区域从此位置开始;必须为非负数
4.size: 要映射的区域大小;必须为非负数且不大于 Integer.MAX_VALUE
有了position与size这两个参数,我们就可以把position设置为原文件的末尾,然后再写入size字节数
现在让我们一起来看下如何在文件末尾写入:

FileChannel fc = new RandomAccessFile("data.txt","rw").getChannel();
long length = fc.size(); //有来设置映射区域的开始位置
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,length,20);
//由于要写入的字符串"Write in the end"占16字节,所以长度设置为20就足够了
mbb.put("Write in the end".getBytes()); //写入新数据
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值