问题描述
有人能解决这个问题吗?我使用 sshpass 在 java 上传输文件。执行这个命令
Process proc = Runtime.getRuntime().exec(new String[] {"sshpass","-p","password","scp","-r",getContext().getServletContext().getRealPath ("/WEB-INF/file/"+today)+"/Name@myip:/cygdrive/d/file"});
并且错误不会使用 runtime.exec 在 java 上显示,但在运行良好的命令行上。
我的代码
try {
Process proc = Runtime.getRuntime().exec(new String[] {"sshpass",getContext().getServletContext().getRealPath("/WEB-INF/file/"+today)+"/ Name@myip:/cygdrive/d/file"});
// System.out.println(sshStr);
BufferedReader read = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
//--------------------check---------------------
printStream(proc.getInputStream(),"OUTPUT");
printStream(proc.getErrorStream(),"ERROR");
//--------------------check---------------------
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
解决方法
使用 Runtime.exec(String)
,无论您添加了哪些引号,字符串参数都会在空格处拆分。您必须改用 Runtime.exec(String[])
。这导致:
Process proc = Runtime.getRuntime().exec(new String[] {
"sshpass","-p","password","scp","-r",getContext().getServletContext().getRealPath("/WEB-INF/file/" + today) + "/ Name@myip:/cygdrive/d/file"
});