-------------------------------1、读取指定文件,写入到字符串中---------------------
String path = "D://Change//checkin//web//news.txt"; //读取文件的路径
String allText = ""; //读取的结果
/*1、根据指定路径,创建一个只读模式(r)的RandomAccessFile对象rafile(可以从任意位置读取或写入文件)[r为只读模式,rw为读写模式]*/
RandomAccessFile rafile = new RandomAccessFile(path,"r");
long length = rafile.length(); //文件长度
/*2、将文件写入到直接字节缓冲区mbf对象中*/
MappedByteBuffer mbf = rafile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, length);
/*3、将字节缓冲区对象mbf传输到指定数组对象bf中*/
byte[] bf = new byte[(int) length]; //声明一个刚好够存放文件流的字节数据
ByteBuffer bbf = mbf.get(bf, 0, (int) length);
/*4、将字节数组bf转换为字符对象allText*/
allText = new String(bf);
-------------------2、将读取的文件内容,写到一个新的文件中-------------------------
String path = "D://Change//checkin//web//news.txt"; //新写入文件的路径
long length = bf.length; //读取的文件流的长度
/*5、根据指定路径,创建一个读写模式(rw)的RandomAccessFile对象rafile,新建指定文件(可以从任意位置读取或写入文件)[r为只读模式,rw为读写模式]*/
RandomAccessFile rafile = new RandomAccessFile(path,"rw");
/*6、创建一个长度为length的直接字节缓冲区mbf对象中*/
MappedByteBuffer mbf = rafile.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, length);
/*7、将指定数组对象bf写入到字节缓冲区对象mbf中,填充新创建的文件*/
ByteBuffer bbf = mbf.put(bf, 0, (int) length);