如何在文件末尾写入新数据,适用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 fos = new FileWriter("data.txt",true); //同样加个参数truefos.write("Write in the end");//该类有不同于FileOutputStream的write(String s)fos.close(); FileChannel fc = new RandomAccessFile("data.txt", "rw").getChannel(); // rw模式//必须用RandomAccessFile("data.txt", "rw").getChannel();//而不能用FileOutputStream.getChannelfc.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(); 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 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()); //写入新数据