我有一个从后端服务器检索字节数组的小程序。此字节数组包含一个动态库(DLL 或 SO,取决于运行小程序的操作系统),必须将其写入磁盘,然后通过调用 System.load() 从磁盘加载。
我需要确保文件在写入磁盘之后和操作系统通过调用 System.load() 加载之前不会被篡改。我在将文件写入磁盘时获得了文件的独占锁,但我的测试表明我必须在调用 System.load() 之前释放此锁,否则将无法加载库。
有什么方法可以在加载文件时保持对文件的锁定?
示例代码:
File f = File.createTempFile("tmp", "");
RandomAccessFile raf = new RandomAccessFile(f, "rwd");
FileChannel channel = raf.getChannel();
FileLock lock = channel.lock(0, Long.MAX_VALUE, false);
// This would be where I write the DLL/SO from a byte array...
raf.write((int)65); // 'A'
raf.write((int)66); // 'B'
raf.write((int)67); // 'C'
System.out.println("Wrote dynamic library to file...");
// Close and release lock
raf.close();
System.out.println("File closed. Lock released.");
// This call fails if the file is still locked.
System.load(f.getAbsolutePath());
任何帮助是极大的赞赏。解决方案(如果有的话)不能是任何操作系统的原生解决方案,但可以在 Java 支持的所有平台上运行。该解决方案与 Java 1.4 兼容也是一个要求。