2016-07-29 42 views
0

當我在許多不同的時間執行一個外部命令時,我一直在努力試圖阻止IO。從一個進程的輸出讀取字節數組

我終於能夠得到它的工作(閱讀很多頁面後,嘗試 不同的方法,其中許多導致阻止io)。

我目前的解決方案(如下)工作。但是我必須預先定義byteArray和輸出(newArray),我必須給它一個大小。問題是, 當我給它一個固定的大小(比如1000)時,它只讀取前1000個字節。 我的問題似乎是範圍和我對數組不變性的理解。有沒有更清晰的方法來讀取命令的輸出成爲一個增長儘可能多的字節數組?

或者,有沒有更好的方法來將InputStream轉換爲byteArray newBytes?

bytes is a predefined byteArray 

var newBytes = new Array[Byte](bytes.length); 

def readJob(in: InputStream) { 
    newBytes = Stream.continually(in.read).takeWhile(_ != -1).map(_.toByte).toArray 

    in.close(); 

} 
def writeJob(out: OutputStream) { 

    out.write(bytes) 
    out.close() 
} 

val io = new ProcessIO(
    writeJob, 
    readJob, 
    _=>()) 

val pb = Process(command) 
val proc = pb.run(io) 
val exitCode = proc.exitValue // very important, so it waits until it completes 

謝謝你提前很多的任何幫助

回答

2

我得到了下面的編譯。

val newBytes = ArrayBuffer[Byte]() 

def readJob(in: InputStream) { 
    newBytes.appendAll(Stream.continually(in.read).takeWhile(_ != -1).map(_.toByte).toArray) 
    in.close() 
} 

def writeJob(out: OutputStream) { 
    out.write(newBytes.toArray) 
    out.close() 
} 

// the rest of the code is unchanged 

我不相信這是最好的方法,但它可能適用於對已有的最小調整。

+0

謝謝。這正是我需要的 – dmg