Merge pull request #5 from Izzette/master

Unlink temp file after loading on POSIX.
This commit is contained in:
Adam Heinrich
2017-09-04 11:03:22 +02:00
committed by GitHub

View File

@@ -24,7 +24,10 @@
package cz.adamh.utils;
import java.io.*;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.ProviderNotFoundException;
/**
* A simple library class which helps with loading dynamic libraries stored in the
* JAR archive. These libraries usualy contain implementation of some methods in
@@ -63,7 +66,7 @@ public class NativeUtils {
String[] parts = path.split("/");
String filename = (parts.length > 1) ? parts[parts.length - 1] : null;
// Split filename to prexif and suffix (extension)
// Split filename to prefix and suffix (extension)
String prefix = "";
String suffix = null;
if (filename != null) {
@@ -79,35 +82,59 @@ public class NativeUtils {
// Prepare temporary file
File temp = File.createTempFile(prefix, suffix);
temp.deleteOnExit();
if (!temp.exists()) {
throw new FileNotFoundException("File " + temp.getAbsolutePath() + " does not exist.");
}
boolean tempFileIsPosix = false;
try {
if (FileSystems.getDefault()
.supportedFileAttributeViews()
.contains("posix")) {
// Assume POSIX compliant file system, can be deleted after loading.
tempFileIsPosix = true;
}
} catch (FileSystemNotFoundException
| ProviderNotFoundException
| SecurityException e) {
// Assume non-POSIX, and don't delete until last file descriptor closed.
}
// Prepare buffer for data copying
byte[] buffer = new byte[1024];
int readBytes;
// Open and check input stream
InputStream is = NativeUtils.class.getResourceAsStream(path);
if (is == null) {
temp.delete();
throw new FileNotFoundException("File " + path + " was not found inside JAR.");
}
// Open output stream and copy data between source file in JAR and the temporary file
OutputStream os = new FileOutputStream(temp);
try {
while ((readBytes = is.read(buffer)) != -1) {
os.write(buffer, 0, readBytes);
}
} catch (Throwable e) {
temp.delete();
throw e;
} finally {
// If read/write fails, close streams safely before throwing an exception
os.close();
is.close();
}
// Finally, load the library
System.load(temp.getAbsolutePath());
try {
// Load the library
System.load(temp.getAbsolutePath());
} finally {
if (tempFileIsPosix)
temp.delete();
else
temp.deleteOnExit();
}
}
}