作业:分散的读和聚集的写实现文件的复制,将sg.txt文件中的内容只复制2kb的大小,且最终形成的新的文件为xinde.txt
package com.rj.bd.zuoye02;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
*
-
@desc 12.分散的读和聚集的写实现文件的复制,将sg.txt文件中的内容只复制2kb的大小,且最终形成的新的文件为xinde.txt
-
@author psh
-
@time 2018-11-6
*/
public class ZuoYe01 {
public static void main(String[] args) throws Exception {
//1.创建多个buffer
long start = System.currentTimeMillis();
ByteBuffer byteBuffer01=ByteBuffer.allocate(1024);
ByteBuffer byteBuffer02=ByteBuffer.allocate(1024);
ByteBuffer[] buffers = {byteBuffer01,byteBuffer02};
//2.分散的去读
String file=“D:/sg.txt”;
RandomAccessFile readacessAccessFile=new RandomAccessFile(file, “rw”);
FileChannel readChannel = readacessAccessFile.getChannel();
//3.聚集的去写
RandomAccessFile writeAccessFile = new RandomAccessFile(“D:/xinde.txt”, “rw”);
FileChannel writeChannel = writeAccessFile.getChannel();
//4.通过读写实现文本文件的复制
int a = 0;
while (readChannel.read(buffers)!=-1)
{
for (int i = 0; i < 1; i++) {
a = a + byteBuffer01.capacity()/1024;
a = a + byteBuffer02.capacity()/1024;
System.out.println(a);
if (a==2) {
buffers[i].flip();
}
}writeChannel.write(buffers); buffers[1].clear(); } //5.关闭对象 writeChannel.close(); readChannel.close(); writeAccessFile.close(); readacessAccessFile.close(); System.out.println("文本复制完成"); long stop = System.currentTimeMillis();
System.out.println(“总共耗时:”+(stop-start));
}
}
package com.rj.bd.zuoye02;
import java.io.File;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.DecimalFormat;
import org.apache.commons.io.FileUtils;
/**
*
-
@desc 利用NIO实现将D:/zp/123.mp4复制到E:/zp/234.mp4,要求能复制成功,且最终将复制后文件的大小显示在控制台上
-
@author psh
-
@time 2018-11-6
*/
public class ZuoYe02 {
public static void main(String[] args) throws Exception {//1.构建输出和输入的通道 FileChannel inChannel = FileChannel.open(Paths.get("D:/zp/123.mp4"), StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("F:/zp/234.mp4"), StandardOpenOption.CREATE,StandardOpenOption.READ,StandardOpenOption.WRITE); //2.两个通道之间的通信:实现的效果就是讲大文件进行了复制 outChannel.transferFrom(inChannel, 0, inChannel.size()); //System.out.println("文件大小为:"+inChannel.size()/1024.0/1024.0+"MB"); //3.关闭对象 outChannel.close(); inChannel.close(); System.out.println("文件复制成功"); File file =new File("F:/zp/234.mp4"); double fileSize = FileUtils.sizeOf(file)/1024.0/1024.0; DecimalFormat dFormat=new DecimalFormat("0.00"); System.out.println("文件的大小为"+dFormat.format(fileSize)+"MB");
}
}