java实现集简单shell命令

目标:用java实现简单的shell命令,做出和终端相似的效果,实现,cd,ls,cat,pwd,grep,echo,copy,mkdir等一些简单的shell命令。
话不多说上代码。
cd功能:

import java.io.File;
import java.io.IOException;
public class cd {
    public static File main(String cmd) throws IOException {
        shell sh=new shell();
        File currentpath = new File(sh.pathname);
        System.out.print("shell:" + currentpath.getAbsolutePath() + ">");
        String echotxt = " ";

            String path = cmd.replaceFirst("cd", "").trim();
            File newpath = new File(path);
            if (newpath.exists()) {
                currentpath = newpath;
                System.out.print("shell"+currentpath.getAbsoluteFile()+">");
                return currentpath;
            } else {
                System.out.println("Error! no such directory!");
                return currentpath;
            }
    }
}

实现shell命令,cd 可是很重要的一部分组成,其他功能都要依靠cd,来实现的哦。
ls功能:

import java.io.File;
public class  ls{
    public static void main(File path){
        String[] num=path.list();
        if(num==null){
            System.out.println("当前目录为空");
        }
        else{
            for(int i=0;i<num.length;i++){
                String str=num[i];
                System.out.println(str);
            }
        }
    }
}

ls实现的功能是打印当前路径的目录,在linux操作系统中ls是一个很重要的命令,所以必须要学会如何使用ls命令。
cat命令:

import java.io.IOException;
import java.io.FileInputStream;
import java.io.File;
public class cat {
    public static void main(File cun,String sum) throws IOException {
        try{
            final String name = sum;
            //获取要打印的文件
            File file = new File(cun,name);
            //建立数据流通道
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] buf = new byte[1024];
            int length = 0;
            //循环读取文件内容,输入流中将最多buf.length个字节的数据读入一个buf数组中,返回类型是读取到的字节数。
            //当文件读取到结尾时返回 -1,循环结束。
            while ((length = fileInputStream.read(buf)) != -1) {
                System.out.print(new String(buf, 0, length));
            }
            //关闭流
            fileInputStream.close();
        }catch (Exception e){
            System.out.println("Error");
        }
    }
}

cat的功能是打印当前目录下的,文本文件,将其打印呈现出来。
grep功能

import java.io.IOException;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class grep {
    public static void main(String patten,File path,String name)throws IOException{
        int LineNumber=0;//定义行数
        Pattern r=Pattern.compile(patten);//使要查找的目标等于r
        File sum=new File(path,name);
        InputStreamReader read=new InputStreamReader(new FileInputStream(sum));
        BufferedReader num=new BufferedReader(read);
        String line=null;
        while((line=num.readLine())!=null) {//判断文件的是否为空,只要不为空就一直查找
            LineNumber++;
            Matcher m = r.matcher(line);//在每一行找寻目标
            if (m.find()) {//如果找到
                System.out.println(LineNumber + " "+line);//就输出目标和行数
            }
        }
    }
}

打印出含有指定字符串的行数和内容。
echo功能:

import java.io.File;
import java.io.IOException;
public class echo {
    public static void main(String echotxt) throws IOException {
        File currentpath=new File("/home/fxl");
        System.out.print("shell:"+currentpath.getAbsolutePath()+">");
                if(echotxt.indexOf('"')==0&&echotxt.lastIndexOf('"')==echotxt.length()-1) {
                    echotxt = echotxt.substring(1, echotxt.length() - 1);
                }
                echotxt=echotxt.replace("\\n","\r\n");
                System.out.println(echotxt);
            }
        }

打印输入的字符串。
pwd功能

import java.io.File;
import java.io.IOException;
public class pwd{
    public static void main(File path){
        String courseFile = null;
        try {
               courseFile = path.getCanonicalPath();//获取文档路径
            } catch (IOException e) //输出异常
        {
               e.printStackTrace();
             }
        System.out.println(courseFile);
    }
}

打印当前工作的路径
mkdir功能

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class mkdir {
    public static void main(String str,File file1) {
        File file=new File(file1,str);//输入的路径
        if(!file.exists()) {//如果这个路径存在的话就创建文件
            file.mkdir();
        }
         //sc.close();
        try{
            BufferedWriter num=new BufferedWriter(new FileWriter(file1.getAbsolutePath()+"/"+str+"/a.txt"));
            //在刚创建的文件内创建一个txt文件
            num.write("hello everyone");//txt文件的内容为hello everyone
            num.close();//关闭并保存文件
        }catch (Exception e){
            System.out.print("ERROR");//如果错误的话就输出ERROR
        }
    }
}

在当前路径内创建一个文件夹
copy功能

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class copy {
    public  static void main(String[] args)throws IOException{
        String dir=null;
        System.out.print("请输入你要复制的文件的路径:");
        Scanner input=new Scanner(System.in);
        dir=input.nextLine();
        FileInputStream sum=new FileInputStream(dir);
        //封装好需要复制的文件路径
        String child=null;
        System.out.print("请输入你要将文件复制到的路径");
        child=input.nextLine();
        FileOutputStream num=new FileOutputStream(child);
        //将文件复制到指定路径下
        byte[] tempt=new byte[sum.available()];//定义字节数组作为缓冲区
        sum.read(tempt);//将文件读入数组中
        num.write(tempt);//从数组中将文件读出
        num.close();//关闭读取
        sum.close();//关闭读入
        File x=new File(child);
        //创建文件对象
        if(x.exists()){//判断文件是否存在
            System.out.println("success copy");//如果存在则成功复制
        }
        else{
            System.out.println("copy the failure");//如果不存在则复制失败
        }
        }

    }

复制指定文件到指定目录。
主目录:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class shell {
    static String pathname;
    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in);
        System.out.print("请输入路径:");
        pathname=input.nextLine();
        File currentpath=new File(pathname);
        System.out.print("/home/fxl");
        String str=input.nextLine();
        str=str+" e";
        String[] strs=str.split(" ");
        while (true) {
            System.out.print(currentpath.getAbsoluteFile()+":");
            switch (strs[0]) {
                case "exit":
                    System.exit(0);
                    break;
                case "copy":
                    copy a = new copy();
                    a.main(null);
                    break;
                case "pwd":
                    pwd b = new pwd();
                    b.main(currentpath);
                    break;
                case "ls":
                    ls c = new ls();
                    c.main(currentpath);
                    break;
                case "mkdir":
                    mkdir d = new mkdir();
                    d.main(strs[1],currentpath);
                    break;
                case "cat":
                    cat e = new cat();
                    e.main(currentpath,strs[1]);
                    break;
                case "grep":
                    grep h = new grep();
                    h.main(strs[1],currentpath,strs[2]);
                    break;
                case "echo":
                    echo i = new echo();
                    i.main(strs[1]);
                    break;
                case "cd":
                    cd j=new cd();
                    currentpath=j.main(strs[1]);
                    break;
            }
            str=input.nextLine();
            str=str+" e";
            strs=str.split(" ");
        }
    }
}

这就是用java实现shell命令的代码了
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
这就是一部分运行的效果了,这里我就不一一演示了,你可以自己去实现一下;

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Shell封装Java代码是指通过Shell脚本来调用和执行Java程序的过程。这样做的好处是可以简化Java程序的执行流程,提高代码的可读性和维护性。 首先,需要在Shell脚本中指定Java的环境变量,确保能够正确地识别和执行Java程序。例如,可以使用`export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64`来指定Java的安装路径。 然后,可以在Shell脚本中使用`java`命令来执行Java程序。需要指定Java类的完整路径和参数。例如,可以使用`java -cp /path/to/class:/path/to/library com.example.MainClass arg1 arg2`来执行Java程序。 在使用Shell封装Java代码时,可以结合其他Shell命令和技术来实现更多功能。例如,可以使用`if`和`else`语句来判断执行条件,使用循环语句来重复执行Java程序,使用`echo`命令输出执行结果等。 此外,Shell脚本还可以通过传递参数的方式来动态地配置Java程序的参数。通过在Shell脚本中定义变量,可以在执行Java程序时传递给程序。例如,可以使用`java -cp /path/to/class:/path/to/library com.example.MainClass $param1 $param2`来传递参数。 总之,通过Shell封装Java代码可以将复杂的Java程序执行过程简化为一个简单Shell脚本。这样做不仅提高了代码的可读性和维护性,还可以方便地进行自动化部署和管理。同时,Shell脚本还提供了丰富的功能和命令,可以更加灵活地控制和配置Java程序的执行流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值