1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2024-11-26 14:02:06 +01:00

Add FileUtils.maybeCreateFileWithParentDirectories(File)

This commit is contained in:
Florian Schmaus 2018-08-17 12:39:28 +02:00
parent a70ae7ab8e
commit fb3009adb2
3 changed files with 26 additions and 28 deletions

View file

@ -207,4 +207,28 @@ public final class FileUtils {
throw new IOException("Could not delete file " + file); throw new IOException("Could not delete file " + file);
} }
} }
public static void maybeCreateFileWithParentDirectories(File file) throws IOException {
File parent = file.getParentFile();
if (!parent.exists() && !parent.mkdirs()) {
throw new IOException("Cannot create directory " + parent);
}
if (file.isFile()) {
return;
}
if (!file.exists()) {
if (file.createNewFile()) {
return;
}
throw new IOException("Cannot create file " + file);
}
if (file.isDirectory()) {
throw new IOException("File " + file + " exists, but is a directory.");
} else {
throw new IOException("File " + file + " exists, but is neither a file nor a directory");
}
}
} }

View file

@ -120,26 +120,12 @@ public class FileBasedOpenPgpMetadataStore extends AbstractOpenPgpMetadataStore
static void writeFingerprintsAndDates(Map<OpenPgpV4Fingerprint, Date> data, File destination) static void writeFingerprintsAndDates(Map<OpenPgpV4Fingerprint, Date> data, File destination)
throws IOException { throws IOException {
if (data == null || data.isEmpty()) { if (data == null || data.isEmpty()) {
FileUtils.maybeDeleteFileOrThrow(destination); FileUtils.maybeDeleteFileOrThrow(destination);
return; return;
} }
if (!destination.exists()) { FileUtils.maybeCreateFileWithParentDirectories(destination);
File parent = destination.getParentFile();
if (!parent.exists() && !parent.mkdirs()) {
throw new IOException("Cannot create directory " + parent.getAbsolutePath());
}
if (!destination.createNewFile()) {
throw new IOException("Cannot create file " + destination.getAbsolutePath());
}
}
if (destination.isDirectory()) {
throw new IOException("File " + destination.getAbsolutePath() + " is a directory.");
}
BufferedWriter writer = null; BufferedWriter writer = null;
try { try {

View file

@ -102,19 +102,7 @@ public class FileBasedOpenPgpTrustStore extends AbstractOpenPgpTrustStore {
FileUtils.maybeDeleteFileOrThrow(file); FileUtils.maybeDeleteFileOrThrow(file);
} }
File parent = file.getParentFile(); FileUtils.maybeCreateFileWithParentDirectories(file);
if (!parent.exists() && !parent.mkdirs()) {
throw new IOException("Cannot create directory " + parent.getAbsolutePath());
}
if (!file.exists()) {
if (!file.createNewFile()) {
throw new IOException("Cannot create file " + file.getAbsolutePath());
}
} else {
if (file.isDirectory()) {
throw new IOException("File " + file.getAbsolutePath() + " is a directory.");
}
}
BufferedWriter writer = null; BufferedWriter writer = null;
try { try {