/**
* 复制文件
* 1.一次读取一个字节,用循环不断读取到没有字节可读
* 2.循环体内,一次写一个字节.
3.完成复制
总结: 但是复制大文件,这样的方法,效率底下
*/
public class CopyDemo1 {
public static void main(String[] args) throws IOException {
RandomAccessFile src = new RandomAccessFile("rafDemo.txt", "r");
RandomAccessFile desc = new RandomAccessFile("rafDemocopy.txt", "rw");
int count = 0;
int bitIndex = 0;
/*定义循环条件,只要当返回的"int整型的低8位" bitIndex值不为-1时,表示src的文件里还有内容*/
while ( (bitIndex = src.read())!= -1){
//满足循环条件,即desc指定的文件开始写入bitIndex的内容
desc.write(bitIndex);
//这里我为了实验写入过程,我把每个字节写入过程输出显示,
count++; //计数器
System.out.println("第"+count+"字节写入完毕");
/* 输出结果:
第1字节写入完毕
第2字节写入完毕
第3字节写入完毕
第4字节写入完毕
第5字节写入完毕
第6字节写入完毕
第7字节写入完毕
第8字节写入完毕
*/
}
}
}
/**
* 复制文件
* 提高读写数据量,减少读写次数,可以提高
* 读写效率
*/
public class CopyDemo2 {
public static void main(String[] args) throws IOException {
RandomAccessFile src = new RandomAccessFile("The.rar", "r");
RandomAccessFile desc = new RandomAccessFile("E:\\Ts.rar", "rw");
//定义个byte数组,存储临时的字节量.
byte[] buf = new byte[1024*50]; //10k缓存
int len = 0;
long start = System.currentTimeMillis();
/*定义循环条件,只要当返回的"int整型的低8位" len值不为-1时,表示src的文件里还有内容*/
while ( (len = src.read(buf))!= -1){
//满足循环条件,即desc指定的文件开始写入buf的内容
desc.write(buf,0,len);
}
long end = System.currentTimeMillis();
System.out.println("复制完毕,耗时 :"+ (end - start)+ "ms");
src.close();
desc.close();
}
}