對於那些我不知道的原因,這是不可能的使用file.rename()之間不同的安裝可怕的移動文件(如sdcard0和sdcard1),這裏是我的解決方案,它適用於我:
if(canRename(f1, f2)) {
if(!f1.renameTo(f2)) {
Log.e(TAG, "Error to move new app: " + f1 + " > " + f2);
}
} else {
try {
copy(f1, f2);
f1.delete();
} catch (Exception ex) {
Log.e(TAG, "Error to move new app: " + f1 + " > " + f2);
}
}
private void copy(final File f1, final File f2) throws IOException {
f2.createNewFile();
final RandomAccessFile file1 = new RandomAccessFile(f1, "r");
final RandomAccessFile file2 = new RandomAccessFile(f2, "rw");
file2.getChannel().write(file1.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, f1.length()));
file1.close();
file2.close();
}
private boolean canRename(final File f1, final File f2) {
final String p1 = f1.getAbsolutePath().replaceAll("^(/mnt/|/)", "");
final String p2 = f2.getAbsolutePath().replaceAll("^(/mnt/|/)", "");
return p1.replaceAll("\\/\\w+", "").equals(p2.replaceAll("\\/\\w+", ""));
}
謝謝。從文檔中可以看出,不同安裝點之間的重命名不起作用。這個問題的目的是要了解還有什麼可以出錯的。 – philipp
@ user1079877我已經使用你的代碼重新命名broadcastreceiver上的圖像,它完美的工作,直到android 6,因爲你知道在運行時檢查權限,所以現在f2.createNewFile(); 引發訪問被拒絕的異常,您有任何優惠嗎? –