Reputation: 105
I want to save the Entire command line logs for a command executed using java, which i am using to send it to a different program via an API. In Eclipse we can achieve this via Run Time Configuration by setting the output file. So , is there a way we can send the entire output from a command line execution and save it in external file?
Upvotes: 2
Views: 410
Reputation: 1297
My two cents elaborating on the answer of Sandeep Patel.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
public class Os {
public static boolean exec(String command, String filePath) {
try (InputStream in = Runtime.getRuntime().exec(command).getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath)))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
return true;
} catch (IOException e) {
return false;
}
}
public static String exec(String command) {
try (InputStream in = Runtime.getRuntime().exec(command).getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); StringWriter sw = new StringWriter()) {
String line;
while ((line = br.readLine()) != null)
sw.write(line + "\n");
return sw.toString();
} catch (IOException e) {
return null;
}
}
public static String exec2(String command) {
try (InputStream in = Runtime.getRuntime().exec(command).getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null)
sb.append(line).append("\n");
return sb.toString();
} catch (IOException e) {
return null;
}
}
public static void main(String[] argv) {
System.out.println(Os.exec2("ls -Fla /"));
}
}
Upvotes: 0
Reputation: 425418
The java application only knows about the arguments passed to it; it knows nothing about JVM options, dynamic environment settings (ie -Dname=value
) etc.
To see the entire command, you would have to use an OS command to look at the running processes and examine its output.
Eg in linux, use long pid = ProcessHandle.current().pid();
then execute "ps"
with args "-p", pid
then parse the output.
Upvotes: 1
Reputation: 5148
Basic example if you are running a command through java code
public static void main(String[] argv) throws Exception {
String command = "ls";
Process child = Runtime.getRuntime().exec(command);
InputStream in = child.getInputStream();
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Filepath")));
String line;
while((line=br.readLine())!=null){
bw.write(line);
bw.newLine();
}
bw.close();
}
Upvotes: 3