![](/img/trans.png)
[英]Having trouble copying an existing sqlite db file from assets to android project
[英]Trouble copying file in Android
我的問題不是如何在Android中創建文件的副本 ,我的問題是為什么它無法創建副本。
我的應用程序下載文件后,正在嘗試將其復制到另一個文件夾(最終用戶可以將文件保存在幾個文件夾中,這就是為什么我下載一次並復制到其余文件夾的原因)。 我確實有原始文件路徑,例如:
/storage/emulated/0/MyAppFolder/FolderCreatedByUser1/theFile.pdf
並試圖將其復制到
/ storage / emulated / 0 / MyAppFolder / FolderCreatedByUser2 /
使用以下代碼(由Robert Nekic改進的代碼):
public static boolean copyFile(File src, File[] dst) {
boolean result = true;
if (src.exists()) {
String srcName = src.getName();
for (File file : dst) {
String to = file.getPath();
try {
File destination = new File(to, srcName);
if (destination.createNewFile()) {
FileChannel srcChnl = new FileInputStream(src).getChannel();
FileChannel dstChnl = new FileOutputStream(destination).getChannel();
dstChnl.transferFrom(srcChnl, 0, srcChnl.size());
srcChnl.close();
dstChnl.close();
} else {
result = false;
System.out.println("Unable to create destination " + destination.getPath());
}
} catch (Exception e) {
result = false;
System.out.println(e.getMessage());
break;
}
}
} else {
result = false;
System.out.println("File " + src.getPath() + " doesn't exist.");
}
return result;
}
該文件存在,但是在將其復制到最終文件時仍然會出錯,例如:
/storage/emulated/0/MyAppFolder/FolderCreatedByUser2/theFile.pdf:打開失敗:ENOENT(無此類文件或目錄)
嘗試打開src文件和/或目標文件時,兩個流均失敗:
FileChannel srcChnl = new FileInputStream(src).getChannel();
FileChannel dstChnl = new FileOutputStream(destination).getChannel();
授予寫權限。 目標文件夾是在下載文件之前創建的,如果未創建目錄,則用戶無法選擇目標。
destination = new File(to, srcName);
創建一個新的File實例,但不創建基礎文件。 您可以通過檢查destination.exists()
進行驗證。 我相信您所需要的是:
destination = new File(to, srcName);
destination.createNewFile();
另外,您的src
路徑字符串操作和代碼前半部分中的內容似乎是不必要的,並且可能會引入一個錯誤,可以通過更簡潔的方式解決該錯誤:
public static boolean copyFile(File src, File[] dst) {
boolean result = true;
if (src.exists()) {
String srcName = src.getName();
for (File file : dst) {
String to = file.getPath();
try {
File destination = new File(to, srcName);
if (destination.createNewFile()) {
FileChannel srcChnl = new FileInputStream(src).getChannel();
FileChannel dstChnl = new FileOutputStream(destination).getChannel();
dstChnl.transferFrom(srcChnl, 0, srcChnl.size());
srcChnl.close();
dstChnl.close();
} else {
result = false;
System.out.println("Unable to create destination " + destination.getPath());
}
} catch (Exception e) {
result = false;
System.out.println(e.getMessage());
break;
}
}
} else {
result = false;
System.out.println("File " + src.getPath() + " doesn't exist.");
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.