日期:2014-05-17  浏览次数:20737 次

java 调用 windows cmd 命令
/**
 * 
 */
package com.gpdi.ipark.utils;

import java.io.File;
import java.io.IOException;



/**
 * @author 喧嚣求静
 *iParking
 * 2012-3-13
 */
public class FileProcessInShell {
	
	/*
	 * java的Runtime.getRuntime().exec(commandStr)可以调用执行cmd指令。 cmd /c dir
	 * 是执行完dir命令后关闭命令窗口。 cmd /k dir 是执行完dir命令后不关闭命令窗口。 cmd /c start dir
	 * 会打开一个新窗口后执行dir指令,原窗口会关闭。 cmd /k start dir 会打开一个新窗口后执行dir指令,原窗口不会关闭
	 */
	/**
	 * fromPathAndcondition "D:"+File.separator+"images"+File.separator+"*.jpg"
	 * toPath "D:"+File.separator+"images"+File.separator+"temp"
	 * 
	 * */
	public static void moveFilesInWindows(String fromPathAndcondition,
			String toPath) throws IOException {
		if (StrFuncs.isEmpty(fromPathAndcondition))
			return;

		File file = new File(toPath);

		if (!file.exists()) {
			if (!file.mkdirs()) {
				System.out.println("创建目录 " + toPath + " 失败");
				return;
			} else {
				if (!file.isDirectory()) {
					System.out
							.println("FileProcessInShell.moveFilesInWindows method param toPath="
									+ toPath + " is not Directory");
					return;
				}

			}
		}

		String condition = fromPathAndcondition + " " + toPath;

		String cmd = "cmd /c  move /Y " + condition;

		try {
			Runtime.getRuntime().exec(cmd);
		} catch (IOException e) {
			System.out.println(fromPathAndcondition + " 移动文件到 " + toPath
					+ " 失败");
			e.printStackTrace();
		}
	}
	/**
	 * condition 代表要删除文件的过滤条件
	 * 如,删除当前目录中所有jpg文件,condition=.\*.jpg
	 * */
	public static void deleteFilesInWindows(String condition){
		
		if(StrFuncs.isEmpty(condition))return ;
		String[] cmdArray = {"cmd", "/c", "del", condition.trim()};  
		   try {
			Runtime.getRuntime().exec(cmdArray);
		} catch (IOException e) {
			
			e.printStackTrace();
		}  
	}
	/**
	 * condition 代表要删除文件的过滤条件
	 * 如,删除当前目录中所有jpg文件,condition=./*.jpg
	 * */
    public static void deleteFilesInLinux(String condition){
		//TODO 
		
	}
}