我正在使用以下代码通过Jsch运行SFTP命令:
public void putfile(){
try {
String command="winscp /script=D:\\command.txt" ;
System.out.println(command);
Runtime rt=Runtime.getRuntime();
rt.exec(command);
}
catch(Exception e) {
System.out.println("Exception in index.jsp:"+e.getMessage());
}
}
我将sample.zip从本地计算机放到Unix服务器上,
command.txt包含:
option confirm off
open sftp:User:password@IP
get G:\sample.zip /MyFolderLocation/
exit
它的工作正常,但每当SFTP进程失败时,我都不会出现任何异常。是否有任何方法可以处理它?
有两种常用的方法来检测您运行的子进程是否遇到错误:
我不知道WinSCP是否在发生错误时设置退出代码,或将消息写入标准输出或标准错误,但是它至少应执行其中之一。(它甚至可能两者都做,这是我期望所有行为良好的过程都可以做的。)您只需要试用WinSCP并查看会发生什么。
我还建议使用aProcessBuilder
代替Runtime.getRuntime().exec(...)
运行命令。如果没有其他要求,则可以将标准错误重定向到标准输出,因此您只有一个流可供读取。
在将其修改为使用ProcessBuilder
,获取进程的退出代码并将命令的输出读入字符串后,代码如下所示:
public void putfile() {
try {
ProcessBuilder builder = new ProcessBuilder("winscp", "/script=D:\\command.txt");
builder.redirectErrorStream(true);
Process process = builder.start();
// read output from the process
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder outputBuilder = new StringBuilder();
String line;
do {
line = reader.readLine();
if (line != null) { outputBuilder.append(line).append('\n'); }
} while (line != null);
reader.close();
String output = outputBuilder.toString();
// inspect output for error messages.
int exitCode = process.waitFor();
// see if exit code is 0 (success) or != 0 (error)
}
catch(Exception e) {
System.out.println("Exception in index.jsp:"+e.getMessage());
}
}
当然,reader
应该封闭起来finally
。为了清楚起见,我没有在上面的代码中这样做。
请注意,在Java中运行子流程时,即使您不关心其内容,也应始终阅读该子流程的输出。如果不这样做,则输出写入的缓冲区可能会填满,这将导致子进程在要写入更多内容时挂起。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句