gpt4 book ai didi

安卓:最佳实践? ,将多个文件从一个文件夹复制到另一个文件夹时,需要很多时间,

转载 作者:行者123 更新时间:2023-11-29 19:07:48 24 4
gpt4 key购买 nike

我正在使用下面的代码将多个文件从一个文件夹复制到另一个文件夹,但这需要太多时间,要求他们实现任何最佳实践以提高速度。我将不胜感激。(注意:我不是在移动文件)

void copyFile(File sourceLocation, File targtLocation) throws IOException {

if (sourceLocation.exists()) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(sourceLocation);
new File(String.valueOf(targtLocation)).delete();
out = new FileOutputStream(targtLocation);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;

while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();

sourceLocation.delete();
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(sourceLocation));
sendBroadcast(scanIntent);
Log.e("debug", "Copy file successful.");

} else {
Log.v("debug", "Copy file failed. Source file missing.");
}
}

最佳答案

终于做到了。当我使用 BufferedOutputStream 和 BufferedInputStream 时,处理时间减半。与输入/输出流不同,它不会为每个字节读/写调用底层系统。相反,它调用一次并缓冲这些流。

void copyFileFast1(File sourceLocation, File targtLocation) throws IOException {

if (sourceLocation.exists()) {
FileInputStream fin = null;
FileOutputStream fout = null;
Log.i("debug","source "+sourceLocation);
Log.i("debug","des "+targtLocation);
try {
fin = new FileInputStream(sourceLocation);
new File(String.valueOf(targtLocation)).delete();
fout = new FileOutputStream(targtLocation);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Copy the bits from instream to outstream
byte[] buf = new byte[2048];
int len;
BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(fout);
BufferedInputStream bufferedInputStream=new BufferedInputStream(fin);
while ((len = bufferedInputStream.read(buf)) > 0) {
bufferedOutputStream.write(buf, 0, len);
}
fin.close();
bufferedOutputStream.close();
fout.close();

sourceLocation.delete();
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(sourceLocation));
sendBroadcast(scanIntent);
Log.e("debug", "Copy file successful.");

} else {
Log.v("debug", "Copy file failed. Source file missing.");
}
}

关于安卓:最佳实践? ,将多个文件从一个文件夹复制到另一个文件夹时,需要很多时间,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46562746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com