如果需要拷貝大文件或文件和所有與文件相關的系統權限,使用java內部的File.copy()將會過於昂貴,因此您可以將所有負載卸載到您的系統中。請嘗試以下技巧 - 首先,將用戶字符串數組作爲exec()的參數嘗試以下技巧:首先,將用戶字符串數組作爲exec()的參數。其次,在使用/ C參數的'cmd'命令後在管道中執行'xcopy'。看看我使isWindows()調用的線附近的示例代碼。
訣竅是您的xcopy命令將在CMD shell內部執行,並且/ C將在成功執行後終止它。關於CMD.exe的更多信息。
public int sysCopyFile(Resource fromResource, Resource toResource) throws ServiceException {
int returnCode = -1;
try {
String[] copyCommand = null;
if (IOUtils.isWindows()) {
copyCommand = new String[] {"cmd", "/C", "copy", "/Y", fromResource.getFile().getAbsolutePath(), toResource.getFile().getAbsolutePath()};
} else if (IOUtils.isUnix() || IOUtils.isMac()) {
copyCommand = new String[] {"/bin/cp", "-pr", fromResource.getFile().getAbsolutePath(),toResource.getFile().getAbsolutePath()};
}
final Process p = Runtime.getRuntime().exec(copyCommand);
new StreamLogger(p.getErrorStream(), log, StreamLogger.WARN);
new StreamLogger(p.getInputStream(), log, StreamLogger.DEBUG);
returnCode = p.waitFor();
if (returnCode != 0) throw new ServiceException("Unable to to copy. Command: {" + copyCommand[0] + "} has returned non-zero returnCode: " + returnCode);
} catch (IOException e) {
throw new ServiceException(e);
} catch (InterruptedException e) {
throw new ServiceException(e);
}
return returnCode;
}
您是否嘗試使用ProcessBuilder?它應該比Runime.exec() – 2011-12-23 22:23:30
也嘗試過...但徒勞無功... – rcs 2011-12-28 23:59:06