Java代码调用Linux命令

1. 调用cp命令

// 使用数组的方式可以解决上传的文件名包含特殊字符 空格等
String[] shell = new String[]{"cp", oldPath, newPath};
Process process = Runtime.getRuntime().exec(shell);
 
// 使用new RunThread方式解决waitFor会阻塞线程或死锁问题
new RunThread(process.getInputStream(), "INFO").start();
new RunThread(process.getErrorStream(), "ERR").start();
 
int value = process.waitFor();
if (value == 0) {
     log.info("复制成功");
 } else {
     log.info("复制失败");
}

public class RunThread extends Thread {
    private InputStream is;
    private String printType;
 
    RunThread(InputStream is, String printType) {
        this.is = is;
        this.printType = printType;
    }
 
    @Override
    public void run() {
        try {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                log.info(printType + ">" + line);
            }
        } catch (IOException ioe) {
            log.info("RunThread error:", ioe);
        }
    }
}

 

你可能感兴趣的:(Java代码调用Linux命令)