1
mirror of https://github.com/CarmJos/EasyConfiguration.git synced 2024-09-19 20:25:51 +00:00

fix(file): 修复 FileConfigProvider#saveResource 文件创建异常的问题。#39

This commit is contained in:
Carm Jos 2023-07-18 00:20:20 +08:00
parent 56557221a4
commit 763fc7c758
2 changed files with 16 additions and 20 deletions

View File

@ -8,6 +8,7 @@ import org.jetbrains.annotations.Nullable;
import java.io.*; import java.io.*;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.nio.file.Files;
import java.util.Objects; import java.util.Objects;
public abstract class FileConfigProvider<W extends ConfigurationWrapper<?>> extends ConfigurationProvider<W> { public abstract class FileConfigProvider<W extends ConfigurationWrapper<?>> extends ConfigurationProvider<W> {
@ -35,10 +36,7 @@ public abstract class FileConfigProvider<W extends ConfigurationWrapper<?>> exte
} }
if (sourcePath != null) { if (sourcePath != null) {
try { saveResource(sourcePath, true);
saveResource(sourcePath, true);
} catch (Exception ignored) {
}
} }
} }
@ -48,28 +46,25 @@ public abstract class FileConfigProvider<W extends ConfigurationWrapper<?>> exte
if (resourcePath.equals("")) throw new IllegalArgumentException("ResourcePath cannot be empty"); if (resourcePath.equals("")) throw new IllegalArgumentException("ResourcePath cannot be empty");
resourcePath = resourcePath.replace('\\', '/'); resourcePath = resourcePath.replace('\\', '/');
InputStream in = getResource(resourcePath);
if (in == null) throw new IllegalArgumentException("The resource '" + resourcePath + "' not exists");
URL url = this.getClass().getClassLoader().getResource(resourcePath);
if (url == null) throw new IllegalArgumentException("The resource '" + resourcePath + "' not exists");
int lastIndex = resourcePath.lastIndexOf('/'); int lastIndex = resourcePath.lastIndexOf('/');
File outDir = new File(file, resourcePath.substring(0, Math.max(lastIndex, 0))); File outDir = new File(file.getParentFile(), resourcePath.substring(0, Math.max(lastIndex, 0)));
if (!outDir.exists() && !outDir.mkdirs()) throw new IOException("Failed to create directory " + outDir); if (!outDir.exists() && !outDir.mkdirs()) throw new IOException("Failed to create directory " + outDir);
if (!file.exists() || replace) { if (!file.exists() || replace) {
try { try (OutputStream out = Files.newOutputStream(file.toPath())) {
URLConnection connection = url.openConnection();
OutputStream out = new FileOutputStream(file); connection.setUseCaches(false);
byte[] buf = new byte[1024]; try (InputStream in = connection.getInputStream()) {
int len; byte[] buf = new byte[1024];
while ((len = in.read(buf)) > 0) { int len;
out.write(buf, 0, len); while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} }
out.close();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} }
} }
} }

View File

@ -1 +1,2 @@
version: 1.0 version: 1.0
test-save: false