Java实现shell命令

目的:
实现以下各个命令的功能:
1.echo打印字符串。同hello命令
2.grep正则匹配。
3.grep “hello” file,检查file文件里每一行,将开头是hello的行打印出来。
4.echo “test\n\string\nfor\ngrep" |grep “string”//将echo 后面的字符串打印内容作为grep的输入参数,会打印输出含有string的行
5.pwd:打印当前目录
6.ls:打印当前目录下所有的文件
7.cd [dir]: 跳转到dir文件夹
8.cat [file]:打印file文件内容
9.mkdir [dir]: 创建文件夹
10.cp [file] [copy]: 复制file中的内容到copy中
各部分代码:
echo:

package com.company;
public class echo {

    public static void main(String str) {
        System.out.println(str);

    }
}

grep:

package com.company;

import java.io.*;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Grep {

        public static void main (String pattern,File path,String name) throws IOException
        {   //int number=0;
            try {
                Pattern r = Pattern.compile(pattern);
                File file=new File(path,name);
                InputStreamReader read = new InputStreamReader(new FileInputStream(file));
                BufferedReader bufferedReader = new BufferedReader(read);
                String line = null;
                //System.out.println("开头含"+pattern+"的行有:");
                while ((line=bufferedReader.readLine()) != null)
                {
                    Matcher m=r.matcher(line);
                    if(pattern.startsWith("^"))
                    {if(m.lookingAt())//开头是否含有
                    {
                        System.out.println(line);
                    }
                    }
                    else
                    {   if(m.find())
                        System.out.println(line);}


                }
            }
            catch (Exception E)
            {System.out.println("grep:"+path+": 没有那个文件或目录");}

        }

    }

pwd:

package com.company;

import java.io.File;

public class pwd
{
    public static void main(File path)
    {

        String str=path.getAbsolutePath();
        System.out.println(str);
    }
}

ls:

package com.company;
import java.io.File;
public  class ls{
       public static void main(File currentpath,String path) {
           SHELL sh=new SHELL();
           String pa=SHELL.pathname;
           char ss[] = path.toCharArray();
           if (ss[0]=='a') path=pa;
           String [] files=currentpath.list();
           for(int i=0;i<files.length;i++){
               File f=new File(currentpath,files[i]);
               if(!f.isHidden()) {
                       String str = files[i];
                       System.out.printf("%-20s", str);

                       if ((i + 1) % 5 == 0)
                           System.out.println();
               }
           }
           System.out.println();
        }

}

cd:

package com.company;

import java.io.File;
import java.io.IOException;

public class cd
{

    public static File main(String cmd) throws IOException {
        SHELL sh=new SHELL();
        String pa=SHELL.pathname;
        File currentpath=new File(pa);
        File newpath=new File(cmd);
        if(newpath.exists()) {
            currentpath = newpath;
            return currentpath;
        }
        else{
            System.out.println("bash: cd: "+cmd+": 没有那个文件或目录");
            return currentpath;
        }
    }
}

cat:

package com.company;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class cat
{
    public static void main(File path,String name)
    {   File input=new File(path,name);
        try {
            BufferedReader bsf = new BufferedReader(new FileReader(input));
            String str = null;
            while ((str = bsf.readLine()) != null) {
                System.out.println(str);
            }
        }
        catch (Exception e)
        {System.out.println("Error");}
    }
}

mkdir:

package com.company;

import java.io.File;

public class mkdir
{
    public static void main(File path,String name) {
        File file = new File(path,name);
        if (!file.exists())
            file.mkdir();
    }
}

cp:

package com.company;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class cp
{
    public static void main (String file1,String copy) throws IOException
    {
        FileInputStream fis=new FileInputStream(file1);
        FileOutputStream fos= new FileOutputStream(copy);
        byte[] lsy =new byte[fis.available()];
        fis.read(lsy);
        fos.write(lsy);
        fis.close();
        fos.close();
        File file=new File(copy);
		/*if (file.exists())
		{
			System.out.println("Success");
		}*/
    }
}

Shell总代码:

package com.company;
import java.io.*;
import java.util.Scanner;
/**
 * this is my first java program
 * @author zhangyifang
 */
public class SHELL {
	static String pathname=null;
    public   static void main(String[] args)throws IOException {
		Scanner input=new Scanner(System.in);
		System.out.println("请输入路径:(eg:/home/zyf)");
		pathname=input.nextLine();
		File currentpath=new File(pathname);
		System.out.print("zyf:"+currentpath.getAbsolutePath()+">");
		String shell=null;
		String[] strings=null;
		shell=input.nextLine();
		shell=shell+" a";
		strings=shell.split(" ");
		while (true) {
			switch(strings[0])
			{ case "exit": System.exit(0);break;//perfect
			  case "echo":// ok
				echo a = new echo();
				if (strings.length >3) {
					Grep a1 = new Grep();
					if (shell.contains("|grep")) {
						a1.main(strings[3], write(strings[1]),"e&g.txt");
					}
					else a.main(shell.substring(5,shell.length()-1));
				}
				else a.main(strings[1]);break;

				case "grep"://ok
					Grep b=new Grep();
					b.main(strings[1],currentpath, strings[2]);
					break;
				case "pwd"://ok
					pwd c=new pwd();
					c.main(currentpath);
					break;
				case "ls"://ok
					ls d=new ls();
					d.main(currentpath,strings[1]);
					break;
				case "cd"://
					cd e=new cd();
					currentpath=e.main(strings[1]);
					break;
				case "cat"://ok
					cat f=new cat();
					f.main(currentpath,strings[1]);
					break;
				case "mkdir"://ok
					mkdir g=new mkdir();
					g.main(currentpath,strings[1]);
					break;
				case "cp"://ok
					cp h=new cp();
					h.main(strings[1], strings[2]);
					break;
				default:System.out.println("Error Input");break;}
			    System.out.print("zyf:"+currentpath.getAbsolutePath()+">");
			    strings=null;
			    shell=input.nextLine();
			    shell=shell+" a";
			    strings=shell.split(" ");

		}

    }
	//写入文件
	public static File write(String str)
	{
		mkdir wr=new mkdir();
	    File file=new File(pathname+"/桌面");
		wr.main(file,"e&g");
		try
		{
			BufferedWriter writer=new BufferedWriter(new FileWriter(pathname+"/桌面/e&g/e&g.txt"));
			writer.write(str);
			writer.close();
		}
		catch (Exception E)
		{
			System.out.println("Error");
		}
		File file1=new File(pathname+"/桌面/e&g");
        return file1;

	}
	}

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值