您可以使用sun.misc.Unsafe類,它可以讓您直接使用JVM內存。
它的構造函數是私有的,所以,你可以得到一個不安全的情況是這樣的:
public static Unsafe getUnsafe() {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (Unsafe)f.get(null);
} catch (Exception e) { /* ... */ }
}
然後,您可以讓您的字符串字節:
byte[] value = []<your_string>.getBytes()
long size = value.length
您現在可以分配內存的大小和寫字符串中的RAM:
long address = getUnsafe().allocateMemory(size);
getUnsafe().copyMemory(
<your_string>, // source object
0, // source offset is zero - copy an entire object
null, // destination is specified by absolute address, so destination object is null
address, // destination address
size
);
// the string was copied to off-heap
來源:https://highlyscalable.wordpress.com/2012/02/02/direct-memory-access-in-java/
可能重複的[Java:popen() - like function?](http://stackoverflow.com/questions/2887658/java-popen-like-function) – ceving