Android 文件复制操作及优化(cpu的占用,资源的释放)

来源:互联网 发布:答案软件 编辑:程序博客网 时间:2024/05/22 06:18
//文件复制操作
public static void copyFile(File sourceFile,File targetFile)throws IOException{
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);
// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
// 缓冲数组
byte[] b = new byte[1024 * 8];
int len;
int i = 0; //
while ((len =inBuff.read(b)) != -1) {
i ++;
outBuff.write(b, 0, len);
if(i == 64){ // 每写512K 时间片停下 留资源给其他IO操作
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
i = 0;
}
}

// 刷新此缓冲的输出流

outBuff.flush();

//关闭流

inBuff.close();

outBuff.close();

output.close();

          input.close();

                b = null;

}

一,当文件很大时会占用IO通道所以因当将时间休息会让其他人上。

二,关闭打开的流,同时将临时申请的中间变量都赋值为null,便于回收,这样做是很有意义的。

原创粉丝点击