这是我将代码从本地复制到远程计算机的代码的一部分
try {
Process cpyFileLocal = Runtime.getRuntime().exec("scp " + rFile+"*.csv" + " root@" + host + ":" + lFile);
InputStream stderr = cpyFileLocal.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR>");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("</ERROR>");
int exitVal = cpyFileLocal.waitFor();
System.out.println("Process exitValue: " + exitVal);
System.out.println("...." + cpyFileLocal.exitValue());
System.out.println("SCP COMMAND "+"scp "+rFile+"*.csv" +" root@"+host+":"+lFile);
System.out.println("Sending complete...");
} catch (Exception ex) {
ex.printStackTrace();
}
输出是......
<ERROR>
/opt/jrms/rmsweb/transfer/cn00/outgoing/*.csv: No such file or directory
</ERROR>
Process exitValue: 1
....1
SCP COMMAND scp /opt/jrms/rmsweb/transfer/cn00/outgoing/*.csv root@10.50.1.29:/opt/jrms/transfer/incoming/
但是当我在本地机器的终端上运行命令时,它工作正常 当我运行 ll 文件时
-rwxr-xr-x 1 freddie freddie 140 Apr 22 09:13 gc00cn00150420092629.csv *
-rwxr-xr-x 1 freddie freddie 105 Apr 22 09:13 gc00cn00150420122656.csv *
请帮助
答案 0 :(得分:1)
当你在bash中使用*
之类的通配符运行命令时,bash会扩展该命令,在你的情况下,将*.csv
替换为以.csv
结尾的文件列表,但是在你的java程序中,这不会发生。
根据this answer,您可以执行以下操作:
scp
或使用整个列表或感谢@James Anderson评论在sh
之前添加scp
。
答案 1 :(得分:0)
如果您使用的是java 7及更高版本,则应使用ProcessBuilder
而不是Runtime.getRuntime().exec()
,并在ProcessBuilder
中指定执行目录:
ProcessBuilder pb = new ProcessBuilder("scp", rFile+"*.csv", "root@" + host + ":" + lFile);
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory("directory where the csv files located");
Process p = pb.start();
答案 2 :(得分:0)
根据this,您应该尝试:
Process cpyFileLocal = Runtime.getRuntime().exec(new String[] {"/bin/sh","-c", "scp " + rFile+"*.csv" + " root@" + host + ":" + lFile});
我使用/bin/sh
和/bin/bash
进行了测试,两者都成功复制了文件