2017-05-01 96 views
-1

我有這樣的代碼:運行bash命令,保存輸出到RAM內存

String command = "dmidecode -t2"; 

try { 
     Process pb = new ProcessBuilder("/bin/bash", "-c", command).start(); 
    } 
catch (IOException e) { 
    e.printStackTrace(); 
} 

我想保存命令RAM的輸出(所以我只能在實時使用它)。如何將輸出保存到RAM中的字符串?

+0

可能重複的[Java:popen() - like function?](http://stackoverflow.com/questions/2887658/java-popen-like-function) – ceving

回答

-1

您可以使用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/

+0

雖然這個鏈接可能回答這個問題,但它更好在這裏包括答案的基本部分,並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/15999083) – EJoshuaS

+1

哦,我沒有想到這種可能性。 好吧,我正在寫一個基於該頁面內容的新答案。 感謝您的建議! –

0

所有相關流都可以使用Process#getOutputStream(),Process#getInputStream(),Process#getErrorStream()之一。

您不應該在乎它們是否保存在RAM中:您可以在進程仍在運行時讀取stdout。

相關問題