【发布时间】:2014-05-07 19:07:41
【问题描述】:
基本上这就是我的输入的样子:
C:> ltf sample.txt
然后Shell v2.0(程序)在C盘创建一个sample.txt文件。
我已经探索了 split() 函数,但我必须从存储在我的数组中的命令验证我的输入。所以我还需要将文件名“存储”在我的数组中。我知道这是不合理的,因为文件名会有所不同。基本上我想问的是,我如何一起接受命令和文件名?这是我当前的代码,只是为了让您了解我正在尝试做什么
package assignment311;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.*;
import javax.swing.JOptionPane;
public class assignment {
/*Data Members*/
public static String[] myData;
public static String CurrentPath;
/*Methods*/
public assignment()
{
myData=new String[13];
myData[0]="ls";
myData[1]="ls -la";
myData[2]="less";
myData[3]="gd";
myData[4]="md";
myData[5]="rnd";
myData[6]="del";
myData[7]="hd";
myData[8]="uhd";
myData[9]="ltf";
myData[10]="nbc";
myData[11]="gdb ";
myData[12]="Tedit";
//initialise currentpath
CurrentPath="C:/";
}
public static void main(String[] args)
{
//initialise data by constructing an object of class
assignment obj=new assignment();
String userInput="";
do
{
//while
//get user input
System.out.print(" "+CurrentPath+"> ");
Scanner scan=new Scanner(System.in);
userInput=scan.nextLine();
String[] stringarray = userInput.split(" ");
/// boolean variable to display information about command validity
boolean isFound=false;
for(int j=0;j<myData.length;j++)
{
if(userInput.equals(myData[j]))
{
isFound=true;
if(stringarray[0].equals("ls"))
{
obj.Run_Ls();
}
if(stringarray[0].equals("gd"))
{
//ask user to enter a folder name
System.out.println("enter a valid folder name");
//get input
String fdname=scan.nextLine();
//get all folders name
File myfile=new File(CurrentPath);
String[] allfiles=myfile.list();
// match user input with folder names
boolean isdirthere=false;
for(int k=0;k<allfiles.length;k++)
{
if(fdname.equals(allfiles[k]))
{
CurrentPath=CurrentPath+"/"+allfiles[k];
isdirthere=true;
}
}
if(!isdirthere)
{
System.out.println("Invalid Folder Name");
}
}
if(userInput.equals("ltf"))
{
System.out.println("Enter valid file name");
String filename=scan.nextLine();
final Formatter x;
try
{
x = new Formatter(filename);
System.out.println("File Created");
}
catch (Exception e)
{
System.out.println("Error man");
}
}
if(userInput.equals("nbc"))
{
}
}
}
if(!isFound)
{
System.out.println("Invalid Command");
}
// scan.close();
//end of while
}
while(!userInput.equals("exit"));
}
public void Run_Ls()
{
File obj=new File(CurrentPath);
String[] ls_result=obj.list();
for(int i=0;i<ls_result.length;i++)
{
System.out.println(ls_result[i]);
}
}
}
【问题讨论】: