[英]copy files from assets folder to sd card in android
我的代碼適用於將文件從資產文件夾復制到 SD 卡。 但是每當我嘗試再次復制時,它只是用新文件替換舊文件而不是重命名它。 我該如何解決? 謝謝
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
}
如果文件存在則覆蓋文件是正常行為,使用fileObject.exists()
方法檢查,如果文件存在選擇另一個文件名,您可以使用System.currentTimeMillis()
方法獲取唯一后綴並將其添加到文件名.
NaN 答案是實現目標的方法之一,只需更改一行即可:
File outFile = new File(getExternalFilesDir(null), filename + System.currentTimeMillis());
另一種方法是增加文件大小的廣告ETERNUM,但如果你是一個適合的工具,這將不適合你的需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.