#java #android #performance #file
Вопрос:
Я загружаю файл с помощью библиотеки PRDownloader на Android. И в своем классе адаптера я использую этот блок кода для обновления индикатора выполнения. И иногда после завершения загрузки функция переименования файла не смогла переименовать .временный файл, потому что ресурс заблокирован.
if (model.getDeviceLocation() != null) {
Executor fileExecutor = Executors.newSingleThreadExecutor();
Handler handler = HandlerCompat.createAsync(Looper.getMainLooper());
fileExecutor.execute(() -> {
File checkFile = new File(model.getDeviceLocation() ".temp");
if (checkFile.isFile()) {
long total = model.getSize();
do {
long percent = checkFile.length() * 100 / total;
String sizeText = Utils.getProgressDisplayLine(checkFile.length(), total);
handler.post(() -> {
holder.desc.setText(sizeText);
holder.progressBar.setProgress(percent);
});
if (!checkFile.isFile()) {
handler.post(() -> notifyItemChanged(holder.getAbsoluteAdapterPosition()));
break;
} else if (model.getStatus() == 2) {
handler.post(() -> notifyItemChanged(holder.getAbsoluteAdapterPosition()));
break;
}
try {
Thread.sleep(300);
} catch (Exception exception) {
exception.printStackTrace();
}
} while (true);
}
});
}
Способ переименования файла:
public static void renameFileName(String oldPath, String newPath) throws IOException {
final File oldFile = new File(oldPath);
try {
final File newFile = new File(newPath);
if (newFile.exists()) {
if (!newFile.delete()) {
throw new IOException("Deletion Failed");
}
}
if (!oldFile.renameTo(newFile)) {
throw new IOException("Rename Failed");
}
} finally {
if (oldFile.exists()) {
//noinspection ResultOfMethodCallIgnored
oldFile.delete();
}
}
}