running cmd commands through java - java

i am trying to save the logcat of an Android device by executing cmd commands through java,although the file i specify in which the logcat to be saved to is never created.Can anybody tell me why this happens?
the cmd command i want to perform is "adb logcat > C:/Users/user1/Desktop/log1.txt".
and the code I use to execute it is:
try {
// create a new array of 4 strings
String[] cmdArray = new String[4];
cmdArray[0] = "adb";
cmdArray[1] = " logcat";
cmdArray[2] = " >";
cmdArray[3] = " C:/Users/amantsakov/Desktop/logcat.txt";
// create a process and execute cmdArray
Process process = Runtime.getRuntime().exec(cmdArray);
} catch (Exception ex) {
ex.printStackTrace();
}

Hope this will work for you
String[] exeCmd = new String[] { "ffmpeg", "-i", "C:\\test\\Veham.mp3",
"-i", "C:\\test\\test.mp4", "-acodec", "copy", "-vcodec",
"copy", "C:\\test\\outPut.mp4" };
ProcessBuilder pb = new ProcessBuilder(exeCmd);
boolean exeCmdStatus = executeCMD(pb);
return exeCmdStatus;
private static boolean executeCMD(ProcessBuilder pb) {
pb.redirectErrorStream(true);
Process p = null;
try {
p = pb.start();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("oops");
p.destroy();
return false;
}
// wait until the process is done
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("woopsy");
p.destroy();
return false;
}
return true;
}// End function executeCMD
these method will help to run cmd command from java.

Related

Java Interacting with Command Propmt [duplicate]

This question already has answers here:
Execute external program through terminal in Java
(4 answers)
Executing another java program from our java program [duplicate]
(3 answers)
Closed 4 years ago.
Using
String cmdString = "cmd.exe /c start python ";
Process p = Runtime.getRuntime().exec(cmdString);
I can open the command prompt and run python. I now want to interact with the command prompt. I have read that using
public static void main(String[] args)
{
BufferedWriter writerToProc;
String scriptPath = "C:\\Users\\MichaelMi\\Documents\\SourceTree\\NODE-Sensor-Configurator\\src\\application\\resources\\BACnet-CMD-Line-Upgrader\\UpgradeApplication.py";
String iniPath = "C:\\Users\\MichaelMi\\Documents\\SourceTree\\NODE-Sensor-Configurator\\src\\application\\resources\\BACnet-CMD-Line-Upgrader\\BACpypes.ini";
String execString = "python " + scriptPath + " --ini " + iniPath;
String cmdString = "cmd.exe /c start " + execString ;
try {
Process p = Runtime.getRuntime().exec(cmdString);
writerToProc = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writerToProc.write(cmdString);
writerToProc.flush();
writerToProc.write("whois\n");
writerToProc.flush();
readErrors(p);
readOutput(p);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readOutput(Process p)
{
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
Runnable task = new Runnable() {
#Override
public void run() {
try {
if(stdInput.ready())
{
stdInput.lines().forEach((l) -> System.out.println(l));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread backgroundThread = new Thread(task);
backgroundThread.setDaemon(true);
backgroundThread.start();
}
public static void readErrors(Process p)
{
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
Runnable task = new Runnable() {
#Override
public void run() {
try {
if(stdError.ready())
{
stdError.lines().forEach((l) -> System.out.println(l));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread backgroundThread = new Thread(task);
backgroundThread.setDaemon(true);
backgroundThread.start();
}
Is supposed to allow me to write to the open command prompt. However this is not working for me. I am getting no exceptions thrown or status errors. I simply do not know how to write to an open command prompt.
I see two problems in your code:
One problem is the used command-line:
cmd.exe /c start python This starts a new cmd.exe instance which itself the uses start to start a detached python process. The detached process is therefore not connected to your BufferedReader/BufferedWriter.
Your second problem is that python does not execute your "1+1" via stdin.
You can simply verify that by creating a file test with the context 1+1\n and execute it on the console: python < test. You will see no output.
See also piping from stdin to a python code in a bash script.
In this case you need to close the input stream before you can read the output streams of the python process. If anyone knows a better way please let us know.
public static void main(String[] args) {
String cmdString = "python";
try {
ProcessBuilder pb = new ProcessBuilder(cmdString);
Process pr = pb.start();
try (BufferedReader readerOfProc = new BufferedReader(
new InputStreamReader(pr.getInputStream()));
BufferedReader errorsOfProc = new BufferedReader(
new InputStreamReader(pr.getErrorStream()))) {
try (BufferedWriter writerToProc = new BufferedWriter(
new OutputStreamWriter(pr.getOutputStream()));) {
writerToProc.write("myVar=1+1\r\n");
writerToProc.write("print(myVar)\r\n");
writerToProc.flush();
} catch (Exception e) {
e.printStackTrace();
}
String s;
while ((s = readerOfProc.readLine()) != null) {
System.out.println("stdout: " + s);
}
while ((s = errorsOfProc.readLine()) != null) {
System.out.println("stdout: " + s);
}
System.out.println("exit code: " + pr.waitFor());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Hope this helps!

Write commands to running process

I've searched quite a bit for answers, but haven't found anything that really helps, and the threads I found were zombies.
My problem: I'm creating a UI for Bukkit servers, but for end-users to execute commands in the server, I have to write to the process using an OutputStreamWriter.
I have all the code, but the command isn't getting sent to the process.
So far, this is the code I'm using to execute the server and get all the streams:
#SuppressWarnings("null")
private void startServer() throws InterruptedException, IOException {
setTitleText("BukkitUI by Beatsleigher [Starting...]");
setStatusImg(ServerState.BOOTING);
Thread.sleep(1000);
setTitleText("BukkitUI by Beatsleigher [Loading components...]");
runServer = true;
process = new ProcessBuilder();
// Set attibutes
process.redirectErrorStream(true);
java.util.List<String> jvmArgs = new ArrayList<>(4);
jvmArgs.add(JVMManager.getJava().toString()); // If you don't know what this does, you should not consider yourself a programmer.
jvmArgs.add("-jar");
jvmArgs.add(JVMManager.getProcessedInitHeapSize()); // Add Java VM arg[0]
//jvmArgs.add(JVMManager.getProcessedMaxHeapSize()); // Add Java VM arg[1]
jvmArgs.add(PreferenceManager.getBukkitLocation().getAbsolutePath()); // Add Java VM arg[2]
jvmArgs.add("-o"); // Add CraftBukkit arg[0]
jvmArgs.add("true"); // Add CraftBukkit arg[1]
process.command(jvmArgs);
// Start process
pr = process.start();
setTitleText("BukkitUI by Beatsleigher [Running]");
consoleWriter = new BufferedWriter(new OutputStreamWriter(pr.getOutputStream()));
processServer();
}
private void processServer() throws IOException {
new Thread() {
#Override
public void run() {
try {
setStatusImg(ServerState.ONLINE);
jTextPane1.setText("");
consoleReader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while ((consoleOutput = consoleReader.readLine()) != null && (runServer)) {
jTextPane1.setText(jTextPane1.getText() + "\n" + consoleOutput);
highlight();
}
jTextPane1.setText(jTextPane1.getText() + "\n[INFO] [BukkitUI] Server has Stopped!");
highlight();
stopServer();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
pr.destroy();
try {
consoleReader.close();
} catch (IOException ex1) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex1);
}
setStatusImg(ServerState.OFFLINE);
setTitleText("BukkitUI by Beatsleigher [ERROR! Server has stopped!]");
}
}
}.start();
}
The server starts and runs fine, I get all the process output I need, but, as mentioned before, any commands I send to the console using following code won't work.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String inputCmd = jTextField1.getText();
try {
if (inputCmd != null | !inputCmd.equals("")) {
if (inputCmd.startsWith("/")) {
String[] cmd = inputCmd.split("/");
consoleWriter.write(cmd[1]);
clearCmd();
return;
} else if (inputCmd.startsWith("cmd;")) {
String[] cmd = inputCmd.split("cmd;");
consoleWriter.write(cmd[1]);
clearCmd();
return;
}
if (inputCmd.startsWith("bcast;")) {
String[] msg = inputCmd.split("bcast;");
consoleWriter.write("broadcast " + msg[1]);
clearCmd();
return;
}
if (inputCmd.startsWith("appnd;")) {
String[] msg = inputCmd.split("appnd;");
jTextPane1.setText(jTextPane1.getText() + "\n[BUKKITUI] " + msg[1]);
clearCmd();
return;
}
if (inputCmd.equals("--h")) { showHelp(); clearCmd(); return; }
consoleWriter.write("say " + inputCmd);
clearCmd();
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Any help with this matter is greatly appreciated.

executing **kill -9 <PID>** command through java is not working

I am executing the below command to kill a process, but its not killing any process.
Command I tried: #kill -9 "2319"
But at the same time when I execute the same command in command prompt its working fine.
private void killProcess()
{
InputStream errorStream = null;
final String taskKill = isWindows() ? InstallerConstants.WIN_TASKKILL : InstallerConstants.LIN_TASKKILL;
try
{
Process process = null;
final String killCMD = taskKill+"\""+getGuiProcess()+"\"";\\kill -9 "2319"
process = runTime.exec(killCMD);
errorStream = process.getErrorStream();
bufferedReader = new BufferedReader(new InputStreamReader(errorStream));
String error = "";
while(bufferedReader.readLine() != null)
{
error = bufferedReader.readLine();
}
if(!(error==null || "".equals(error)))
{
logger.error(error);
}
}
catch (IOException ioException) {
logger.error(ioException.getMessage(), ioException);
}
finally
{
try
{
if(bufferedReader!=null)
{
bufferedReader.close();
}
if(errorStream!=null)
{
errorStream.close();
}
}
catch (IOException ioException) {
logger.error(ioException.getMessage(), ioException);
}
}
}
Please help to overcome this problem.
You need to specify the absolute path to the kill command
/bin/kill may be?
$ whereis kill //output will show you where kill command is.
do you get any errors btw?

firing a command through terminal in Ubuntu using Java Runtime.exec

This is fairly simple in Windows, but a little tricky in Linux. I am using
Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "java -classpath /home/4/byz/Orc" });
where Orc is the class file with a main function.
But nothing happens. Are there any settings ? Am I doing something wrong ?
I wish the java program to run in the terminal.
EDIT
Here is the solution:
String[] cmdArray = {"gnome-terminal","java -classpath /home/r/byz/ Orchestrator"};
try {
Runtime.getRuntime().exec(cmdArray);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So basically, we have to use gnome-terminal ..
I believe this is already resolved, however I'll post an answer:
How to Run:
executeCommand(new String[]{"/bin/bash", "-c", "java -classpath /home/4/byz/Orc"});
Method:
public String executeCommand(String[] cmd) {
StringBuffer theRun = null;
try {
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
theRun = output.append(buffer, 0, read);
}
reader.close();
process.waitFor();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return theRun.toString().trim();
}
Let me know if this helps!

Running external program

What's the difference between running programs using java and run it using the command line? In the first case it does not work, but in the second case it works fine.
Java:
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("../../../my/prog \"//10.124.12.15/C:/output/*\" ../../../input/345 -N -A");
DataInputStream bis = new DataInputStream(proc.getInputStream());
int _byte;
while ((_byte = bis.read()) != -1)
System.out.print((char)_byte);
proc.waitFor();
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
AND command:
../../../my/prog "//10.124.12.15/C:/output/*" ../../../input/345 -N -A
Try using absolute path. Maybe that's your problem.
Thanks all, I solved my problem:
try {
String cmd="/progs/my/prog //10.124.12.15/C:/output/* /temp/input/345 -N -A"
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(
new String[]{"/usr/bin/bash", "-c", cmd, "1>/dev/null 2>&1"});
proc.waitFor();
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}

Categories