[英]Executing Linux Commands in java
我需要將特定模式的文件從一位導演復制到另一位導演
文件格式: "nm.cdr.*(asterisk)-2014-08-16-14*(asterisk).gz"
命令: "cp " + inputPath + filesPattern + " " + destPath;
如果我使用特定文件而不是使用*,那么它可以正常工作(對於單個文件),但是使用*模式則無法正常工作。
編輯1:我嘗試以下代碼:
public void runtimeExec(String cmd)
{
StringBuffer output = new StringBuffer();
Process p;
try
{
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
}
catch (IOException | InterruptedException e)
{
LogProperties.log.error(e);
}
}
星號是外殼程序解釋的內容,因此您需要使用外殼程序作為主進程,Java中該進程的命令行類似於bash -c '/origin/path/nm.cdr.*-2014-08-16-14*.gz /destination/path'
。
現在,如果您嘗試在單個字符串中使用此命令將不起作用,則需要使用String[]
而不是String
。 因此,您需要執行以下操作:
1:將方法的簽名更改為使用String[]
:
public void runtimeExec(String[] cmd)
2:使用此值為cmd
調用方法:
String[] cmd = new String[] {"bash", "-c",
"cp " + imputPath + filesPattern + " " + destPath};
無法確切看到作為命令傳遞的內容,但是在Linux上通常需要將命令和參數拆分為字符串數組,例如:
String[] cmd = {"cp", inputPath+filesPattern, destPath};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.