Nov 3, 2009

Running shell command from Java program

Following program runs the shell copy command "cp" from a java program:

import java.util.regex.*;
import java.io.*;


class ExecDemo {
public static void main(String args[]) {
Runtime r = Runtime.getRuntime();
Process p = null;
try {
File fin = new File("sampleNames.txt");
FileInputStream fis = new FileInputStream(fin);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine = = null;
String destinationPath = "output/" + "ls_log_untruncated_reshape" + "/";
System.out.println(destinationPath);
while((aLine = in.readLine()) != null) {
String filePath = "input/" +aLine + "/"+ aLine + "_"+"ls_log_untruncated_reshape.txt";
System.out.println(aLine);
String command = "cp " + filePath + " " + destinationPath;
System.out.println(command);
p = r.exec(command);
}

}catch (FileNotFoundException e) {
System.out.println("Cannot find the input file.");
}
catch (Exception e) {
System.out.println("Error running the command.");
}
}
}


References :
Reference 1
Reference 2

No comments:

Cat

Ragdoll Cat         Persian Cat     Finish Cat