You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.9 KiB
Java

3 years ago
/**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 have the program create a separate external process that performs the command. You can create the separate process using the code provided below:**/
import java.io.*;
public class AProcess
{
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java OSProcess <command>");
System.exit(0);
}
// args[0] is the command
ProcessBuilder pb = new ProcessBuilder(args[0]);
Process process = pb.start();
// obtain the input and output streams
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ( (line = br.readLine()) != null)
System.out.println(line);
br.close();
}
}
/**The following code contains the basic operations of a command-line shell. The main() method presents the prompt prompt> and waits to read input from the user. The program is terminated when the user enters <Control><C>.**/
import java.io.*;
public class ABasicShell
{
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 they entered
System.out.print("prompt>");
commandLine = console.readLine();
// if they entered a return, just loop again
if (commandLine.equals(""))
continue;
/**
The basic 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
*/
}
}
}