Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Based on http://frommyplayground.com/how-to-load-native-jni-library-from-jar by Adam Heirnich <adam@adamh.cz>
- */
- public class NativeUtils {
- private final static String DIR_NATIVES = "lwjgl-natives";
- private NativeUtils() {}
- public static File createTempDir() throws IOException {
- final File tempDir = File.createTempFile(DIR_NATIVES, "");
- tempDir.delete();
- tempDir.mkdir();
- tempDir.deleteOnExit();
- return tempDir;
- }
- public static void loadLibraryFromJar(File parent, String library) throws IOException {
- if (!library.startsWith("/")) throw new IllegalArgumentException("The path to be absolute (start with '/').");
- final String filename = library.substring(library.lastIndexOf('/')); // Obtain filename from path
- if (filename == null) // Check if the filename is okay
- throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
- final File temp = new File(parent, filename); // Prepare temporary file
- temp.createNewFile();
- temp.deleteOnExit();
- if (!temp.exists()) throw new FileNotFoundException("File " + temp.getAbsolutePath() + " does not exist.");
- final byte[] buffer = new byte[1024]; // Prepare buffer for data copying
- int readBytes = 0;
- final InputStream is = NativeUtils.class.getResourceAsStream(library); // Open and check input stream
- if (is == null)
- throw new FileNotFoundException("File " + library + " was not found inside JAR.");
- final OutputStream os = new FileOutputStream(temp); // Open output stream and copy data between
- try { // source file in JAR and the temporary file
- while ((readBytes = is.read(buffer)) != -1)
- os.write(buffer, 0, readBytes);
- } finally { // If read/write fails, close streams
- os.close(); // safely before throwing an exception
- is.close();
- }
- }
- public static void deleteOldDir() {
- final FileFilter tmpDirFilter = new FileFilter() {
- public boolean accept(File pathname) {
- return pathname.getName().startsWith(DIR_NATIVES);
- }
- };
- final String tmpDirName = System.getProperty("java.io.tmpdir");
- File[] tmpFiles = new File(tmpDirName).listFiles(tmpDirFilter);
- for (File f : tmpFiles) delete(f);
- }
- private static void delete(File file) {
- if (file.isDirectory())
- for (File f : file.listFiles())
- delete(f);
- else file.delete();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement