我有一个Java程序在我的Swift程序的后台运行。 Java程序可以在命令行中读取用户输入。启动后如何在jar中传递“命令”或文本行?
就像下面的程序从Java程序中读取的方式一样,然后如何“回复”呢?
let b = Bundle.main
let path = b.path(forResource: "myjar", ofType: "jar")!
NSLog("%@", "jar path : \(path)")
task.launchPath = "/usr/bin/java"
task.arguments = ["-jar", path]
let pipe = Pipe()
task.standardOutput = pipe
let errorPipe = Pipe()
task.standardError = errorPipe
task.launch()
let outHandle = pipe.fileHandleForReading
outHandle.waitForDataInBackgroundAndNotify()
var progressObserver : NSObjectProtocol!
progressObserver = NotificationCenter.default.addObserver(
forName: NSNotification.Name.NSFileHandleDataAvailable,
object: outHandle, queue: nil){
notification -> Void in
let data = outHandle.availableData
if data.count > 0 {
if let str = String(data: data, encoding: String.Encoding.utf8) {
NSLog("%@", str)
}
outHandle.waitForDataInBackgroundAndNotify()
} else { NotificationCenter.default.removeObserver(progressObserver)
}
}
然后我尝试了以下方法而没有运气:
pipe.fileHandleForWriting.write("text to send to java program".data(using: String.Encoding.utf8)
答案 0 :(得分:0)
您非常接近。如果您只是添加了代码<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="toggle-element">
<div class="wrap">
<a href="#" class="navbtns prev" title="Go to Next Page">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50"><path d="M25,50A25,25,0,1,0,0,25,25,25,0,0,0,25,50ZM25,2A23,23,0,1,1,2,25,23,23,0,0,1,25,2Zm-3,9V39L32,25Z" style="fill-rule:evenodd"/></svg>
</a>
<a href="#" class="navbtns next" title="Go to Previous Page">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50"><path d="M25,50A25,25,0,1,1,50,25,25,25,0,0,1,25,50ZM25,2A23,23,0,1,0,48,25,23,23,0,0,0,25,2Zm3,9V39L18,25Z" style="fill-rule:evenodd"/></svg>
</a>
</div>
</div>
<div id="container1">
Scroll down to <b>#container2</b>
</div>
<div id="container2">
This is <b>#container2</b>
</div>
<div id="container3">
Scroll up to <b>#container2</b>
</div>
,该代码将无法工作,因为该管道是您分配给pipe.fileHandleForWriting.write("text to send to java program"...
的管道。
您需要创建另一个standardOutput
对象,将其分配给Pipe
,然后写入:
standardInput