May I get all comment to understand please? (Its java program, Thank you) packag
ID: 3871351 • Letter: M
Question
May I get all comment to understand please?
(Its java program, Thank you)
package pa11;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
*
* @author narayanthapa
*/
public class PA11 {
public static void main(String [] args) throws IOException {
String[] commandList = {"ls"};
UserIOHandler userIOHandler = new UserIOHandler();
UserProcessCreator processCreator = new UserProcessCreator(commandList, "/Users/narayanthapa/Desktop");
processCreator.startProcess();
userIOHandler.handleEvent(processCreator);
}
}
class UserProcessCreator {
private ProcessBuilder proBuilder;
private Process process;
private String[] commandList;
public UserProcessCreator(String[] commandList, String directory) {
this.proBuilder = new ProcessBuilder(commandList);
this.proBuilder.directory(new File(directory));
this.commandList = commandList;
}
public void setDirecotry(String directory) {
this.proBuilder.directory(new File(directory));
}
public void startProcess()
throws IOException {
this.process = proBuilder.start();
}
public Process getProcess() {
return this.process;
}
public String[] getCommand() {
return this.commandList;
}
public void waitFor() {
try {
int exitValue = process.waitFor();
System.out.println(" Exit Value is " + exitValue);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class UserIOHandler {
public UserIOHandler() {
super();
}
public void handleEvent(UserProcessCreator processCreator)
throws IOException {
Process process = processCreator.getProcess();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
System.out.printf("Output of running %s is: ", Arrays.toString(processCreator.getCommand()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
processCreator.waitFor();
}
}
Explanation / Answer
If the command is "ls" it will display files under the passed directory.
If command is "pwd" it will display present working directory.