命令行工具

程序解析

该工具实现了基本的6种文件操作
主方法:运行后,创建一个CommondTool的对象,调用start()方法

ICommod接口(6种操作)

    public boolean list();//列出一个目录下的所有文件和其大小
    public boolean mkdir(String path);//创建一个目录
    public boolean copy(String scr,String des);//将一个文件复制到另一个文件
    public boolean remove(String path);//删除一个文件
    public boolean cd_to_child(String path);//进入子目录
    public boolean cd_to_parent();//返回上一个目录

ICmd接口

定义6种指令
并创建一个数组保存

    //定义指令
    String LS = "ls";
    String MKDIR = "mkdir";
    String COPY = "copy";
    String RMDIR = "rmdir";
    String CD = "cd";
    String CDP = "cd..";
    //保存所有的指令
    String[] Commonds = new String[]{LS,MKDIR,COPY,RMDIR,CD,CDP};

CommondTool类

首先实现接口ICommond,接口包含6种方法分别对应6种操作,6种方法如上
定义一个字符作为初始目录位置
比如我的桌面
再定义一个字符作为当前所在目录位置
方便6种方法的操作
构建方法实现对当前目录的赋值,将初始位置给它

start方法的构建
用户输入指令后,进行读取,我们创建一个类CommondOperation进行相关操作
它的对象命名为operation

6种方法的构建
通常需要地址参数
参数通过监听者回调CommondOeration中方法读取的数据(指令,文件地址等)来进行具体的实现

    //默认目录
    private static final String DESKTOP_PATH = "C:/Users/cs/Desktop";
    //当前目录
    private StringBuilder Current_Path = null;
    
    public CommondTool(){
        Current_Path = new StringBuilder(DESKTOP_PATH);
    }
    
    //启动工具
    public void start(){
        //创建读取指令的对象
        CommondOperation operation = new CommondOperation();
        
        System.out.println("欢迎使用该命令行工具");
        while(true){
            showParent();//显示前一个路径
            
            try {
                operation.readCommond(this);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println(e.getMessage());
            }
        }
        
    }
    private void showParent(){
        //获取最后一个
        int start = Current_Path.lastIndexOf("/");
        String parent = Current_Path.substring(start);
        parent += "#";
        System.out.print(parent);
    }

    @Override
    public boolean list() {
        // TODO Auto-generated method stub
        File[] files = FileManager.getInstance().list(Current_Path.toString());
        for(File file : files){
            String name = file.getName();//获取文件名
            long size = file.length();//获取文件长度
            long kb = size/1024;
            long by = size % 1024;
            System.out.print(name);
            for(int i = 0;i < 40 - name.length();i ++){//保持文件大小在同一列,中英文混合则无效
                System.out.print(" ");
            }
            System.out.println(kb + "." + by + "kb");
        }
        return false;
    }

    @Override
    public boolean mkdir(String path) {
        // TODO Auto-generated method stub
        String Dir_Path = Current_Path + "/" + path;
        FileManager.getInstance().mkdir(Dir_Path);
        System.out.println("创建成功");
        return false;
    }

    @Override
    public boolean copy(String src, String des) {
        // TODO Auto-generated method stub
        String Src_Path = Current_Path + "/" + src;
        String Des_Path = Current_Path + "/" + des;
        FileManager.getInstance().copy(Src_Path, Des_Path);
        
        return false;
    }

    @Override
    public boolean remove(String path) {
        // TODO Auto-generated method stub
        String Dir_Path = Current_Path + "/" + path;
        FileManager.getInstance().remove(Dir_Path);
        System.out.println("删除成功");
        return false;
    }

    @Override
    public boolean cd_to_child(String path) {
        // TODO Auto-generated method stub
        Current_Path.append("/");
        Current_Path.append(path);
        System.out.println("进入子目录"+Current_Path);
        return false;
    }

    @Override
    public boolean cd_to_parent() {
        // TODO Auto-generated method stub
        int start = Current_Path.lastIndexOf("/");
        int end = Current_Path.length();
        Current_Path.delete(start,end);
        return false;
    }

CommondOperation类

首先定义一个字符串列表List和Scanner对象,不进行赋值
在构建方法中对它们赋值,其中列表赋值为ICmd的指令数组,以便使用List的方法判断指令是否存在

定义一个监听者listener
private ICommond listener;
只要实现了ICommond接口的类都能作为监听者(比如CommondTool)

定义读取指令方法readCommond,给予参数ICommond listener作为监听者,使用this.listener = listener来接收监听者
所以,在CommondTool中start方法里,创建完CommondOperation对象后,调用方法readCommond(this),将自己作为监听者传递过去

然后解析指令获得具体的指令和文件地址
再根据具体指令使用监听者listener(CommondTool)的6种方法,参数已经解析出来
6种方法具体的实现在CommondTool中实现

    private List<String> commonds;
    //获取输入信息
    private Scanner mScanner;
    public CommondOperation(){
        mScanner = new Scanner(System.in);
        //将普通的Array类型转化为list类型
        commonds = Arrays.asList(ICmd.Commonds);
    }
    //回调对象
    private ICommond listener;
    //接收读取指令
    public void readCommond(ICommond listener) throws CommondNotExistException, CommondArgumentErrorException{
        this.listener = listener;
        //接收指令
        String commond = mScanner.nextLine();
        //解析指令
        parseCommond(commond);
    }
    public void parseCommond(String commond) throws CommondNotExistException, CommondArgumentErrorException{
        //将指令以空格做分割符分开
        String[] componts = commond.split(" ");
        
        //获取指令
        String cmd = componts[0];
        
        //判断指令是否存在
        if(!commonds.contains(cmd)){
            //不存在
            throw new IException.CommondNotExistException("指令不存在");
        }
        
        //存在
        //cd
        if(cmd.equals(ICmd.CD)){
            if(componts.length != 2){
                throw new IException.CommondArgumentErrorException("cd参数错误");
            }
            listener.cd_to_child(componts[1]);
        }
        //cd..
        if(cmd.equals(ICmd.CDP)){
            if(componts.length != 1){
                throw new IException.CommondArgumentErrorException("cd..无需参数");
            }
            listener.cd_to_parent();
        }
        //mkdir
        if(cmd.equals(ICmd.MKDIR)){
            if(componts.length != 2){
                throw new IException.CommondArgumentErrorException("mkdir参数错误");
            }
            listener.mkdir(componts[1]);
        }
        //rm file
        if(cmd.equals(ICmd.RMDIR)){
            if(componts.length != 2){
                throw new IException.CommondArgumentErrorException("rmdir参数错误");
            }
            listener.remove(componts[1]);
        }
        //ls
        if(cmd.equals(ICmd.LS)){
            if(componts.length != 1){
                throw new IException.CommondArgumentErrorException("ls无需参数");
            }
            listener.list();
        }
        //copy
        if(cmd.equals(ICmd.COPY)){
            if(componts.length != 3){
                throw new IException.CommondArgumentErrorException("copy参数错误");
            }
            listener.copy(componts[1],componts[2]);
        }
    }

FileManager类

为了代码的封装性以及代码的可读性
将大部分对于文件的操作方法写在该类里
供CommonTool调用

    private static FileManager manager;
    
    private FileManager(){};
    
    public static FileManager getInstance(){
        if(manager == null){
            synchronized(FileManager.class){
                if(manager == null){
                    manager = new FileManager();
                }
            }
        }
        return manager;
    }
    public boolean mkdir(String path){
        File file = new File(path);
        if(file.exists()){
            return false;
        }
        return file.mkdir();//若前几级目录不存在,则不执行;使用mkdirs()可以创建路径上所有不存在的目录
    }
    
    public boolean remove(String path){
        File file = new File(path);
        if(!file.exists()){
            return false;
        }
        return file.delete();
    }
    
    public File[] list(String path){
        File file = new File(path);
        if(!file.exists()){
            return null;
        }
        return file.listFiles(new FilenameFilter(){

            @Override
            public boolean accept(File dir, String name) {
                // TODO Auto-generated method stub
                if(name.endsWith("txt")){//自己选择过滤条件,这里是只要文本文件
                    return true;
                }
                return false;
            }
            
        });
    }
    public boolean copy(String src,String des){//拷贝
        File file1 = new File(src);
        File file2 = new File(des);
        if(!file1.exists()){//不存在
            System.out.println("文件不存在");
            return false;
        }else if(file1.isFile() && !file2.isDirectory()){//是文件
            copyFile(src,des);
            System.out.println("复制成功");
        }else if(file1.isDirectory() && !file2.isFile()){//是目录
            copyDir(src,des);
            System.out.println("复制成功");
        }else{
            System.out.println("复制出错");
        }
        
        return false;
    }
    private boolean copyFile(String src,String des){
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try{
            //创建输入输出流
            fis = new FileInputStream(src);
            bis = new BufferedInputStream(fis);
            fos = new FileOutputStream(des);
            bos = new BufferedOutputStream(fos);
            //创建buffer
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = bis.read(buffer)) != -1){
                bos.write(buffer);
                System.out.println("请稍等...");
                }
            bos.flush();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                bis.close();
                fis.close();
                bos.close();
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return true;
    }
    private void copyDir(String src,String des){
        File file1 = new File(src);
        File file2 = new File(des);
        file2.mkdir();
        for(File file : file1.listFiles()){
            copyFile(file.getAbsolutePath(),des+"/"+file.getName());
        }
    }

IException类(自己定义的异常)

包括指令未找到,指令给的参数不符合等,提示内容按照实际情况来写

    static class CommondNotExistException extends Exception{
        public CommondNotExistException(String s){
            super(s);
        }
    }
    static class CommondArgumentErrorException extends Exception{
        public CommondArgumentErrorException(String s){
            super(s);
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。