|
|
今天试着写了个java版的cmd,其实核心代码就是用RunTime类的exec()方法,不过觉得目录转换的模拟还是很有趣,“cd..”命令我还没写好.

代码如下:
JavaCmd.java
package com.cmd;import java.io.*;/** * 模拟cmd的类 * @author lupin * @version 1.0 2009-12-25 */public class JavaCmd { public static Process execCmd(String command){ //执行cmd命令的方法 JavaCmd.changDir(command); Runtime run = Runtime.getRuntime(); Process pro =null; try {pro = run.exec("cmd /c" + command,null,new File(System.getProperty("user.dir")));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return pro; } public static void showResult(Process pro){ //回显命令执行结果的方法InputStream is = pro.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));String s = null;try {s = br.readLine();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} while(s != null){ System.out.println(s); try {s = br.readLine();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} } } public static void showWindow(){ //显示cmd窗口 System.out.println("Microsoft Windows XP [版本 5.1.2600]"); System.out.println("<c> 版权所有 1985-2001 Microsoft Corp."); String strHome = System.getProperty("user.home"); System.setProperty("user.dir", strHome); String strDir = System.getProperty("user.dir"); System.out.print(strDir + ">"); } public static void changDir(String str){ //转换目录的方法 if(str.indexOf("dir") < 0 && str.endsWith(":")){ System.setProperty("user.dir", str + "\\"); } else if(str.indexOf("cd") >= 0 && str.indexOf(":") >= 0){ int i = 3; String str1 = str.substring(i); System.setProperty("user.dir",str1); } else if(str.indexOf("cd") >= 0 && str.indexOf(":") < 0){ String dir = System.getProperty("user.dir"); String temp = dir.substring(0,2); String tempStr = str.substring(3); System.setProperty("user.dir", temp + tempStr); } else if(str.indexOf("cd /") == 0){ String dir = System.getProperty("user.dir"); String dirTmp = dir.substring(0, 3); System.setProperty("user.dir", dirTmp); } else if(str.indexOf("cd..") == 0){ } }}
StartCmd.java
package com;import java.util.Scanner;import com.cmd.*;public class StartCmd {/** * @param args */public static void main(String[] args) {Scanner input = new Scanner(System.in);JavaCmd.showWindow(); while(true){ String command =input.nextLine(); Process pro = JavaCmd.execCmd(command); JavaCmd.showResult(pro); String strDir = System.getProperty("user.dir"); System.out.print(strDir + ">"); }}} |
|