Skip to content

Commit f2dc846

Browse files
committed
Added resourceToFile
1 parent 7baf525 commit f2dc846

1 file changed

Lines changed: 26 additions & 4 deletions

File tree

src/main/java/io/github/intisy/utils/utils/FileUtils.java

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,8 @@
22

33
import io.github.intisy.simple.logger.StaticLogger;
44

5-
import java.io.BufferedReader;
6-
import java.io.File;
7-
import java.io.FileReader;
8-
import java.io.IOException;
5+
import java.io.*;
6+
import java.net.URL;
97
import java.nio.charset.Charset;
108
import java.nio.file.AccessDeniedException;
119
import java.nio.file.Files;
@@ -90,6 +88,30 @@ public static void copyFolder(File source, File destination) {
9088
throw new RuntimeException(e);
9189
}
9290
}
91+
92+
public static File resourceToFile(Class<?> resourceClass, String path) {
93+
URL resourceUrl = resourceClass.getClassLoader().getResource(path);
94+
assert resourceUrl != null;
95+
String[] split = path.split("\\.");
96+
String suffix = path.split("\\.")[split.length - 1];
97+
String prefix = path.substring(0, suffix.length() - 1);
98+
try {
99+
File tempFile = File.createTempFile(prefix, suffix);
100+
try (OutputStream outputStream = Files.newOutputStream(tempFile.toPath())) {
101+
byte[] buffer = new byte[1024];
102+
int bytesRead;
103+
try (InputStream stream = resourceUrl.openStream()) {
104+
while ((bytesRead = stream.read(buffer)) != -1) {
105+
outputStream.write(buffer, 0, bytesRead);
106+
}
107+
}
108+
}
109+
return tempFile;
110+
} catch (IOException e) {
111+
throw new RuntimeException(e);
112+
}
113+
}
114+
93115
public static void deleteFolder(File folder) {
94116
// Check if the given File object represents a directory
95117
if (folder.isDirectory()) {

0 commit comments

Comments
 (0)