public class RafDemo2 {
public static void main(String[] args) throws IOException {
RandomAccessFile rafRead = new RandomAccessFile("./k.mp3","r");
RandomAccessFile rafWrite = new RandomAccessFile("./k.mp3","rw");
int d;
long start = System.currentTimeMillis();
while ((d=rafRead.read())!=-1){
rafWrite.write(d);
}
long end = System.currentTimeMillis();
System.out.println("用时"+(start-end));
rafRead.close();
rafWrite.close();
}
}
- 以上方法复制内容极慢,是将源文件一字节一字节复制到内存中,然后再复制到目标文件。
优化文件复制
/*
* 优化文件复制
* 创建缓存,减少读写数据的次数
* 单字节读写是一种随机读写读写形式
* 一组字节读写是块读写形式
* */
public class CopyDemo2 {
public static void main(String[] args) throws IOException {
RandomAccessFile rafRead = new RandomAccessFile("./Kalimba.mp3","r");
RandomAccessFile rafWrite = new RandomAccessFile("./Kalimab_cp.mp3","rw");
/*
* int read(byte[] data)
* 一次性读取给定字节数组长度的字节量,并存到该数组中
* 返回实际读取到的字节量
* 如果返回-1表示已经读取到了末尾(没读取到数据)
*
* void write(byte[] data)
* 将给定的字节数组中的数据写入文件中
*
* void write(byte[] data, int offset, int len)
* 将给定的字节数组中的数据,从下标为offset的位置开始
* 一次性写入len个长度
* */
//定义缓存
byte[] data = new byte[1024*10];
int len; //每次读取到的字节数
while ((len = rafRead.read(data))!=-1){
//将读取到的信息写入
rafWrite.write(data,0,len);
}
long end = System.currentTimeMillis();
rafRead.close();
rafWrite.close();
}
}
- 用时大大缩短,利用数组一次性读取大量数据。