move File vis shell command - Java Native OS

Java examples for Native OS:Shell Command

Description

move File vis shell command

Demo Code


//package com.java2s;

import java.io.IOException;

public class Main {
    public static void main(String[] argv) throws Exception {
        String sourceFile = "java2s.com";
        String destDir = "java2s.com";
        mvFile(sourceFile, destDir);//  w w w.  j a  va 2 s  .  co  m
    }

    private static String osName = System.getProperty("os.name")
            .toUpperCase();
    private static String OS_WINDOWS = "WINDOWS";

    public static void mvFile(String sourceFile, String destDir)
            throws IOException, InterruptedException {
        StringBuffer sb = new StringBuffer(256);
        if (osName.indexOf(OS_WINDOWS) >= 0) {
            sourceFile = "\"" + sourceFile + "\"";
            sb.append("cmd.exe /C  move ")
                    .append(sourceFile.replaceAll("/", "\\\\")).append(" ")
                    .append(destDir.replaceAll("/", "\\\\"));
        } else {
            sb.append("mv ").append(sourceFile).append(" ").append(destDir);
        }
        System.out.println(sb.toString());
        execSystemCommon(sb.toString());
    }

    private static void execSystemCommon(String command)
            throws IOException, InterruptedException {
        try {
            Process proc = Runtime.getRuntime().exec(command);
            proc.waitFor();
        } catch (IOException e) {
            throw e;
        } catch (InterruptedException exp) {
            throw exp;
        }
    }
}

Related Tutorials