第一题若利用映射的话,程序会蛮简洁而且方便扩展。
接近题目要求的程序如下:
import java.lang.reflect.*;
import java.io.*;
import java.util.*;
class MiniDOS {
public static void main(String[] args) {
new MiniDOS().run();
}
public void run() {
Scanner scn = new Scanner(System.in);
while (true) {
String prompt = "[ " + cwd + " ] >> ";
System.out.print(prompt);
String line = scn.nextLine().trim();
if (line.length() > 0 && ! line.equals(prompt.trim()))
processInput(line);
}
}
private void processInput(String input) {
String[] tokens = input.split("\\s+", 2);
String cmd = tokens[0].toLowerCase();
try {
if (! isSupportedCommand(cmd))
throw new Exception("'" + cmd + "' is an invalid command");
Method method = SupportedCommands.class.getMethod(
cmd, tokens.length == 2 ? new Class[]{File.class} : null);
Object[] argumentsForMethodInvocation = null;
if (tokens.length == 2) {
File f = new File(tokens[1]);
f = f.isAbsolute() ? f : new File(cwd, f.getPath());
if (! f.exists())
throw new IOException("'" + f + "' doesn't exist");
argumentsForMethodInvocation = new Object[]{f.getCanonicalFile()};
}
method.invoke(new SupportedCommands(), argumentsForMethodInvocation);
}
catch (NoSuchMethodException e) {
printError("wrong number of argument for '" + cmd + "'");
}
catch (Exception e) {
Throwable cause = e.getCause(); // 为了应付 InvocationTargetException
printError(cause != null ? cause.getMessage() : e.getMessage());
}
}
private void printError(String message) {
System.err.println( "Error: " + message);
}
private File cwd = new File(System.getProperty("user.dir")); // 工作目录
private boolean isSupportedCommand(String cmd) {
return Arrays.toString(SupportedCommands.class.getMethods())
.contains("SupportedCommands." + cmd + "(");
}
/*
* SupportedCommands 类里定义的所有方法都是程序支持的常规命令。
*/
private class SupportedCommands {
public void dir() {
for (File f: cwd.listFiles())
System.out.printf( "%s %9s %9s %s\n",
new Date(f.lastModified()),
f.isDirectory() ? "<DIR>" : "",
f.isDirectory() ? "" : f.length(),
f.getName()
);
}
public void cd(File file) throws IOException {
if (! file.isDirectory())
throw new IOException("'" + file + "' isn't a directory");
cwd = file;
}
public void del(File file) throws IOException {
if (! file.delete())
throw new IOException("deletion failed");
}
public void type(File file) throws IOException {
for (Scanner fs = new Scanner(file); fs.hasNextLine(); )
System.out.println(fs.nextLine());
}
public void exit() {
System.exit(0);
}
}
}
温馨提示:答案为网友推荐,仅供参考