Program in C ++ or Java that works as a Unix command interpreter?

-1

I wanted to know how to do, through object classes, a C ++ or Java program that is able to implement the following functions:

  • string pwd() : returns the full path from the root in the same format as Unix.

  • void ls() : shows by screen each file, directory or link of the current directory, one in each line.

  • void cd(string path) : change the path to another directory, it can be the parent directory ( path=".." ), the current directory ( path="." ), a directory from the root ( path="/...." ) or a directory subdirectory of the current directory.

  • void stat(string elemento) : shows by screen the size of the file, directory or link that is passed as a parameter, you can also pass a route to another element of another directory.

  • void vim(string file, int tamanyo) : change the size of a file within the current route only, if it does not exist, create it new.

  • void mkdir(string directorio) : create a directory within the current route only.

  • void ln(string origen, string destino) : creates a link named "destination" that links to the source element, "destination" can not be a complete path but "source" yes, that is, the element "source" can be in another directory.

  • void rm(string elemento) : delete an item within the current route or you can pass a complete route, if it is a file, delete it directly, if it is a link, delete the link but not the link, and if is a directory removes the directory with all its contents.

There must be 4 different classes: Directorio , Archivo , Enlace and Ruta (the constructor will be a directory that will act as root).

All the above operations are used on the class Ruta .

The main file I have already done in both C ++ and Java, only missing the implementation of the classes, here I attach both.

C ++:

#include <string>
#include <vector>
#include <iostream>
#include <sstream>

#include "ruta.h"

using namespace std;

int main()
{
    Directorio raiz("");
    Ruta ruta(raiz);

    for (bool done=false; !done; )
    {
        string         line,arg;
        vector<string> cmd;

        cout << "~> " << flush;

        getline(cin,line);
        istringstream iss(line);
        while(getline(iss,arg,' ')) cmd.push_back(arg);

        if (cin.eof())
        {
            done = true;
            continue;
        }
        if (cmd.size()<1)
            continue;

        try
        {
            if (cmd[0]=="pwd")
            {
                cout << ruta.pwd() << endl;
            }
            if (cmd[0]=="ls")
            {
                ruta.ls();
            }
            if (cmd[0]=="cd")
            {
                 ruta.cd(cmd.at(1));
            }
            if (cmd[0]=="stat")
            {
                if (cmd.size()>1)
                    ruta.stat(cmd.at(1));
                else
                    ruta.stat(".");
            }
            if (cmd[0]=="vim")
            {
                 ruta.vim(cmd.at(1),atoi(cmd.at(2).c_str()));
            }
            if (cmd[0]=="mkdir")
            {
                 ruta.mkdir(cmd.at(1));
            }
            if (cmd[0]=="ln")
            {
                 ruta.ln(cmd.at(1),cmd.at(2));
            }
            if (cmd[0]=="rm")
            {
                 ruta.rm(cmd.at(1));
            }
            if (cmd[0]=="exit")
            {
                done = true;
            }
        }
        catch (arbol_ficheros_error& e)
        {
             cerr << e.what() << endl;
        }
        catch (out_of_range& e)
        {
             cerr << e.what() << endl;
        }
    }
    cout << endl;

    return 0;
 }

Java:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Main {
    public static void main(String[] args) {
    Directorio raiz;
    Ruta ruta;
    try {
        raiz = new Directorio("");
        ruta = new Ruta(raiz);
    } catch (ExcepcionArbolFicheros e) { return; }

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    boolean end = false;

    while (!end)
    { 
         System.out.print(ruta.pwd()+"> ");
         try {
             String[] argv = br.readLine().split(" ");
             if (argv[0].equals("pwd")) {
                 System.out.println(ruta.pwd());
             } else if (argv[0].equals("ls")) {
                 ruta.ls();
             } else if (argv[0].equals("cd")) {
                 ruta.cd(argv[1]);
             } else if (argv[0].equals("stat")) {
                 if (argv.length > 1) ruta.stat(argv[1]);
                 else ruta.stat(".");
             } else if (argv[0].equals("vim")) {
                 ruta.vim(argv[1], Integer.parseInt(argv[2]));
             } else if (argv[0].equals("mkdir")) {
                 ruta.mkdir(argv[1]);
             } else if (argv[0].equals("ln")) {
                 ruta.ln(argv[1],argv[2]);
             } else if (argv[0].equals("rm")) {
                 ruta.rm(argv[1]);
             } else if (argv[0].equals("exit")) {
                 end = true;
             } else {
                 System.out.println("Comando desconocido");
             }
        } catch(ExcepcionArbolFicheros e) {
             System.out.println(e);
        } catch(IOException e) {
             System.out.println("Error de entrada-salida");
        } catch (java.lang.ArrayIndexOutOfBoundsException e) {
             System.out.println("Error sintactico: parametros insuficientes");
        }
     }
   }
};
    
asked by Elena Saura 11.04.2016 в 20:14
source

3 answers

1

Well, I do not think the resolution of the problem should be done by calling the operating system by invoking the relevant command (the same thing is wrong), among other things because if Java is portable, the commands between operating systems are not, and therefore you should try to perform the functionality through the use of Java.

Regardless of this, I propose the following classes as required, including one more.

The class Path , represents a path to a directory, file or link and is immutable , that is, once created it can not be modified, it is created from of a String object. Some validation could be added.

public class Ruta {
  private final String path;

  public Ruta(String path) {
    this.path=path;
  }

  public String getPath() {
    return path;
  }
}

All other classes extend from the AbstractFileBase class, except the Route class. They all have a common constructor, a rm () method that works the same for all, since a Directory , a File or a Link are removed in the same way and an abstract method stat () that has a different implementation in each case, would be something like this:

public abstract class AbstractFileBase {
  protected File file;

  public AbstractFileBase(Ruta ruta) {
    file=new File(ruta.getPath());
  }

  public void rm(Ruta ruta) {
    file=new File(ruta.getPath());
    if(file.exists()) {
        file.delete();
    }
  }

  public abstract String stat() throws IOException;

}

The Directory class implements its own methods:

public class Directorio extends AbstractFileBase {
  public Directorio(Ruta ruta) {
    super(ruta);
  }

  public String pwd() throws IOException {
    return file.getCanonicalPath();
  }

  public void mkdir(String path) {
    // :TODO
  }

  public List<String> ls() {
    List<String> files=new ArrayList<String>();
    for(File file:file.listFiles()) {
        if(file.isDirectory()) {
            files.add("d - "+file.getName());
        }
        else {
            files.add("f - "+file.getName());
        }
    }
    return files;
  }

  public String cd(Ruta ruta) throws IOException {
    file=new File(ruta.getPath());
    return pwd();
  }

  @Override
  public String stat() throws IOException {
    // :TODO aqui crear la informacion estadistica que se desee
    return "Soy un directorio";
  }

}

The File class implements its own methods:

public class Archivo extends AbstractFileBase {
  public Archivo(Ruta ruta) {
    super(ruta);
  }

  @Override
  public String stat() throws IOException {
    // :TODO aqui crear la informacion estadistica que se desee
    return "Soy un directorio";
  }

  public void vim(String path,int size) throws IOException {
    // :TODO creo que con la versión Java 7 de File es fácil de implementar
  }

}

The class Link implements its own methods:

public class Enlace extends AbstractFileBase {
  public Enlace(Ruta ruta) {
    super(ruta);
  }

  public void ln(String newDirectory) {
    // :TODO
  }

  @Override
  public String stat() throws IOException {
    // :TODO aqui crear la informacion estadistica que se desee
    return "Soy un directorio";
  }

}
  • Finally, if you can not implement all the requested methods with the File class of the JDK, you can try it with FileUtils of Apache Commons IO
  • For your class Main you can create the application CLI (Command Line Interface) style very easily using the library Apache Commons CLI
answered by 12.04.2016 в 01:20
0

You could use the next class

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExecuteShellComand {


public String executeCommand(String command) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader = 
                        new BufferedReader(new InputStreamReader(p.getInputStream()));

                    String line = "";           
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

}

}

and to use those functions would be something like this:

ExecuteShellCommand executor = new ExecuteShellCommand();
// para pwd
executor.executeCommand("pwd");
//para ls
executor.executeCommand("ls");
// etc etc...

Now you just have to create the classes you mention and execute the commands as I showed above

Source: link

    
answered by 11.04.2016 в 20:30
0

That I advise you to have a txt and in each line of this have a shell command, when entering the entry you compare with each line of the txt with this example link and to execute the command in java

    Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");
    
answered by 12.04.2016 в 16:10