Add FileUtils.maybeDeleteFileOrThrow(File)

This commit is contained in:
Florian Schmaus 2018-08-17 12:27:31 +02:00
parent affdcb0557
commit a70ae7ab8e
4 changed files with 15 additions and 25 deletions

View File

@ -196,4 +196,15 @@ public final class FileUtils {
throw new FileNotFoundException("File " + file.getAbsolutePath() + " not found."); throw new FileNotFoundException("File " + file.getAbsolutePath() + " not found.");
} }
} }
public static void maybeDeleteFileOrThrow(File file) throws IOException {
if (!file.exists()) {
return;
}
boolean successfullyDeleted = file.delete();
if (!successfullyDeleted) {
throw new IOException("Could not delete file " + file);
}
}
} }

View File

@ -18,7 +18,6 @@ package org.jivesoftware.smackx.ox.store.filebased;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Date; import java.util.Date;
@ -68,12 +67,7 @@ public class FileBasedOpenPgpKeyStore extends AbstractOpenPgpKeyStore {
File file = getPublicKeyRingPath(owner); File file = getPublicKeyRingPath(owner);
if (publicKeys == null) { if (publicKeys == null) {
if (!file.exists()) { FileUtils.maybeDeleteFileOrThrow(file);
return;
}
if (!file.delete()) {
throw new IOException("Could not delete file " + file.getAbsolutePath());
}
return; return;
} }
@ -91,12 +85,7 @@ public class FileBasedOpenPgpKeyStore extends AbstractOpenPgpKeyStore {
File file = getSecretKeyRingPath(owner); File file = getSecretKeyRingPath(owner);
if (secretKeys == null) { if (secretKeys == null) {
if (!file.exists()) { FileUtils.maybeDeleteFileOrThrow(file);
return;
}
if (!file.delete()) {
throw new IOException("Could not delete file " + file.getAbsolutePath());
}
return; return;
} }

View File

@ -122,12 +122,7 @@ public class FileBasedOpenPgpMetadataStore extends AbstractOpenPgpMetadataStore
throws IOException { throws IOException {
if (data == null || data.isEmpty()) { if (data == null || data.isEmpty()) {
if (!destination.exists()) { FileUtils.maybeDeleteFileOrThrow(destination);
return;
}
if (!destination.delete()) {
throw new IOException("Cannot delete file " + destination.getAbsolutePath());
}
return; return;
} }

View File

@ -99,12 +99,7 @@ public class FileBasedOpenPgpTrustStore extends AbstractOpenPgpTrustStore {
File file = getTrustPath(owner, fingerprint); File file = getTrustPath(owner, fingerprint);
if (trust == null || trust == Trust.undecided) { if (trust == null || trust == Trust.undecided) {
if (!file.exists()) { FileUtils.maybeDeleteFileOrThrow(file);
return;
}
if (!file.delete()) {
throw new IOException("Could not delete file " + file.getAbsolutePath());
}
} }
File parent = file.getParentFile(); File parent = file.getParentFile();