[英]reading from the output of a process into a byteArray
当我多次执行外部命令时,我一直在努力尝试阻塞IO。
我终于能够使它工作(阅读了很多页面,尝试了不同的方法后,许多方法导致io阻塞)。
我当前的解决方案(如下)有效。 但是我必须用输出(newArray)预定义byteArray,并且必须给它一个大小。 问题是,当我给它一个固定大小(例如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
非常感谢您的帮助
我得到以下内容进行编译。
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
我不认为这是最好的方法,但是通过对您已有的内容进行最小的调整,它可能是可行的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.