Question

Creating a Shell Interface Using Java This project consists of modifying a Java program so that...

Creating a Shell Interface Using Java

This project consists of modifying a Java program so that it serves as a shell interface that accepts user commands and then executes each command in a separate process external to the Java virtual machine.

Overview

A shell interface provides the user with a prompt, after which the user enters the next command. The example below illustrates the prompt jsh> and the user’s next command: cat Prog.java. This command displays the file Prog.java on the terminal using the UNIX cat command. jsh> cat Prog.java Perhaps the easiest technique for implementing a shell interface is to have the program first read what the user enters on the command line (here, cat Prog.java) and then create a separate external process that performs the command. We create the separate process using the ProcessBuilder() object, as illustrated in Figure 3.13. In our example, this separate process is external to the JVM and begins execution when its run() method is invoked. A Java program that provides the basic operations of a command-line shell is supplied in Figure 3.37. The main() method presents the prompt jsh> (for java shell) and waits to read input from the user. The program is terminated when the user enters <Control><C> .

import java.io.*; public class SimpleShell { public static void main(String[] args) throws java.io.IOException { String commandLine; BufferedReader console = new BufferedReader (new InputStreamReader(System.in)); // we break out with while (true) { // read what the user entered System.out.print("jsh>"); commandLine = console.readLine(); // if the user entered a return, just loop again if (commandLine.equals("")) continue; /** The steps are: (1) parse the input to obtain the command and any parameters (2) create a ProcessBuilder object (3) start the process (4) obtain the output stream (5) output the contents returned by the command */ } } }

This project is organized into three parts:

(1) creating the external process

modify the main() method in the code above so that an external process is created and executes the command specified by the user. initially, the command must be parsed into separate parameters and passed to the constructor for the ProcessBuilder object.

(2) modifying the shell to allow changing directories

the cd command allows a user to change current directories. yourt shell interface must support this command. for example, if the current directory is /usr/tom and the user enters cd music, the current directory becomes /usr/tom/music . Subsequent commands relate to this current directory. Program must first check the new path being specified is a valid directory and if not, then display an error message. the following commands must be supported:

cd - return to a directory (home/user/1)

cd ~- return to the home directory

cd..- go up one level in directory tree

cd ../.. - go up 2 levels

cd/ - go to root directory

the home directory for the current user can be obtained by nvoking the static getProperty() method in the System class : System.getProperty("user.dir")

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program Screenshot:

SimpleShell.java

Code to copy:

/*

* Part (1) creating the external process and

* executing the command in that process

*/

import java.io.*;

import java.util.*;

public class SimpleShell

{

       public static void main(String[] args) throws java.io.IOException

       {

              String commandLine;

              BufferedReader console = new BufferedReader

                           (new InputStreamReader(System.in));

              // we break out with <control><C>

              while (true)

              {

                     // read what the user entered

                     System.out.print("jsh>");

                     commandLine = console.readLine();

                     // if the user entered a return, just loop again

                     if (commandLine.equals(""))

                           continue;

                     // (1) parse the input to obtain the command and

                     // any parameters

                     StringTokenizer token = new StringTokenizer(commandLine);

                     ArrayList<String> commandList = new ArrayList<String>();

                     //read the tokens and add to the list

                     while (token.hasMoreTokens())

                     {

                           commandList.add(token.nextToken());

                     }

                    

                     String[] commands = commandList.toArray(new String[0]);

                     // (2)create a ProcessBuilder object

                     ProcessBuilder pb = new ProcessBuilder(commands);   

                     // (3) start the process

                     Process process = pb.start();

                     // (4) Obtain the output stream

                     InputStream inStream = process.getInputStream();

                     InputStreamReader inStreamReader = new InputStreamReader(inStream);

                     // (5) output the contents returned by the command

                     BufferedReader br = new BufferedReader(inStreamReader);

                     String line;

                     while ((line = br.readLine()) != null)

                     {

                           System.out.println(line);

                     }

                     br.close();

              }

       }

}

*Part (1) creating the external process and * executing the command in that process import java.io.; import java.util.*; public class SimpleShell public static void main (String[] args) throws java.io.IOException String commandLine; BufferedReader console-new BufferedReader (new InputstreamReader (System. in) ); // we break out with while (true) // read what the user entered System.out.print ("jsh>") CommandLine = console. readLine() ; // if the user entered a return, just loop again if (commandLine.equals ("")) continue // (1) parse the input to obtain the command and // any parameters StringTokenizer token- new StringTokenizer (commandLine) ArrayList commandList new ArrayList(); //read the tokens and add to the list while (token.hasMoreTokens ()) commandList.add (token.nextToken )) String [ commandscommandList.toArray (new String [0]); // (2) create a ProcessBuilder object ProcessBuilder pb new ProcessBuilder (commands) // (3) start the process Process processpb.start)i

Add a comment
Know the answer?
Add Answer to:
Creating a Shell Interface Using Java This project consists of modifying a Java program so that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Project 1: Implementing a Shell 1 Overview In this individual project you will have to design...

    Project 1: Implementing a Shell 1 Overview In this individual project you will have to design and implement a simple shell command interpreter called mysh. The basic function of a shell is to accept lines of text as input and execute programs in response. The shell must be able to execute built-in commands in a process different from the one executing mysh. 2 Requirements When first started, your shell should initialize any necessary data structures and then enter a loop...

  • Unix questions, i need help on Hint: Commands to study to answer this question: predefined shell...

    Unix questions, i need help on Hint: Commands to study to answer this question: predefined shell variables, and .profile script file, echo SHELL, HOME, PATH, MAIL and TERM are predefined shell variables. You can use the value of a shell variable in a shell command putting $ in front of it. For example, to display the value of the HOME directory of the user, specify $HOME in the echo command like echo $HOME. Do not give just the value of...

  • Overview Writing in the C language, implement a very basic shell, called smash. In this project,...

    Overview Writing in the C language, implement a very basic shell, called smash. In this project, we will work on processing strings and using the appropriate system calls. Build System setup Before we can start writing code we need to get our build system all setup. This will involve writing a very simple makefile. You should leverage your Makefile project for this part of the assignment! Write a Makefile that provides the three targets listed below all - The default...

  • Java Project In Brief... For this Java project, you will create a Java program for a...

    Java Project In Brief... For this Java project, you will create a Java program for a school. The purpose is to create a report containing one or more classrooms. For each classroom, the report will contain: I need a code that works, runs and the packages are working as well The room number of the classroom. The teacher and the subject assigned to the classroom. A list of students assigned to the classroom including their student id and final grade....

  • Java program Program: Grade Stats In this program you will create a utility to calculate and...

    Java program Program: Grade Stats In this program you will create a utility to calculate and display various statistics about the grades of a class. In particular, you will read a CSV file (comma separated value) that stores the grades for a class, and then print out various statistics, either for the whole class, individual assignments, or individual students Things you will learn Robustly parsing simple text files Defining your own objects and using them in a program Handling multiple...

  • Update the program in the bottom using C++ to fit the requirements specified in the assignment....

    Update the program in the bottom using C++ to fit the requirements specified in the assignment. Description For this assignment, you will be writing a single program that enters a loop in which each iteration prompts the user for two, single-line inputs. If the text of either one of the inputs is “quit”, the program should immediately exit. If “quit” is not found, each of these lines of input will be treated as a command line to be executed. These...

  • Project 4-4 In this hands-on project, you make and view links to files and directories. Switch to...

    Project 4-4 In this hands-on project, you make and view links to files and directories.Switch to a command-line terminal (tty2) by pressing Ctrl+Alt+F2 and log in to the terminal using the user name of root and the password of secret.At the command prompt, type cd samples and press Enter. Next, type ls -F at the command prompt and press Enter. What files do you see? Next, type ls -l at the command prompt and press Enter. What is the link...

  • Objective : Write a C Shell script which copies all files(*.java and *.class) from your home dire...

    Objective : Write a C Shell script which copies all files(*.java and *.class) from your home directory to a new one, and Analyze the new directory information such as number of files, user permissions, and disk usage. Sample Output:                                                    << CS Directory Analysis >>      Date:   ============================================================ Current Directory: /home/tomss New Directory Created : /home/tomss/pgm01 File information Total Number of files : 22 files Directory files:   0 files Plain text files:   10 files File have read permissions: 3 files File have...

  • Write a program in Java according to the following specifications: The program reads a text file...

    Write a program in Java according to the following specifications: The program reads a text file with student records (first name, last name and grade on each line). Then it prompts the user to enter a command, executes the command and loops. The commands are the following: "print" - prints the student records (first name, last name, grade). "sortfirst" - sorts the student records by first name. "sortlast" - sorts the student records by last name. "sortgrade" - sorts the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT