I want to use two Runtime in same method. The second uses the result of the first. I return the results of in two files (*.txt). The result of execution of the first is ok, but the file of the second is empty.
The code used is given below:
public void applicationpackage() {
try {
Process process = Runtime.getRuntime().exec(
new String[] { "/bin/sh", "-c",
"ls " + pathPackage + "/*.apk" });
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
File f = new File(pathPackage + "/packagename.txt");
PrintWriter writer = new PrintWriter(f, "UTF-8");
String line = reader.readLine();
while ((line != null)) {
System.out.println(line);
applicationPackage.add(line);
writer.println(line);
line = reader.readLine();
Process p = Runtime.getRuntime().exec(new String[]{
"/bin/sh", "-c", "cut -d. -f2,3 <<<" + line
});
p.waitFor();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
File file = new File(pathPackage +"/application.txt");
PrintWriter w = new PrintWriter(file, "UTF-8");
String l = r.readLine();
while(l!= null){
w.println(l);
w.println("toto");
l = r.readLine();
}
name+= "cut -d. -f2,3 <<<" + line +" &";
System.out.println("toto" + name);
}
System.out.println("toto" + name);
writer.close();
} catch (IOException | InterruptedException e1) { }
}
If your file is empty, it usually means your PrintWriter has not got autoflush set, or you have not closed the writer. The last reference to w is w.println("toto");. Add w.close() to your code.
Also when you instantiate a PrintWriter you should pass in a boolean value at the constructor level to indicate that the PrintWriter should flush after every operation.
Related
Executor exec = new DefaultExecutor();
exec.setWorkingDirectory("/var/java/apache-tomcat-7.0.47/webapps/Telegram/tg")
CommandLine cl = new CommandLine("bin/telegram-cli -k tg-server.pub -W -U root");
int exitvalue = exec.execute(cl);
How can I get output of this command:
exec.execute(cl);
and run other related commands on telegram-cli command prompt e.g. contact_list, msg contact "Hello world";
It looks to me as though it would be easier just to use ProcessBuilder instead.
ProcessBuilder pb = new ProcessBuilder("bin/telegram-cli","-k","tg-server.pub","-W","-U","root");
pb.directory(new File("/var/java/apache-tomcat-7.0.47/webapps/Telegram/tg"));
Process p = pb.start();
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(p.getOutputStream()),true)) {
String line = null;
pw.println("contact_list");
while ((line = br.readLine()) != null) {
System.out.println("line = " + line);
}
}
Update
It looks like the writes with PrintWriter need to be flushed. You can do this by calling pw.flush() or adding the second argument true to the PrintWriter constructor. I don't know the commands for telegram-cli, but you need to add one that will produce an output you can use to identify when to quit. Here's an example using /bin/sh.
ProcessBuilder pb = new ProcessBuilder("/bin/sh");
Process p = pb.start();
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(p.getOutputStream()),true)) {
String line = null;
pw.println("ls");
pw.println("pwd");
pw.println("echo quit"); // this gives me output I can test for to break the loop
pw.flush();
while ((line = br.readLine()) != null && !line.contains("quit")) {
System.out.println("line = " + line);
}
}
int retcode = p.waitFor();
System.out.println("process ended with " + retcode);
Produces this output:
line = build
line = build.xml
line = dist
line = manifest.mf
line = nbproject
line = src
line = /home/shackle/NetBeansProjects/JavaApplication20
process ended with 0
I know you can use use following to run a command for linux in java and get the output from the command you just ran.
Process p = Runtime.getRuntime().exec("host -t a " + domain);
p.waitFor();
StringBuffer sb = new StringBuffer();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
sb.append(line + "\n");
}
I am however wondering, is there any simpler way of getting the output from the command that was ran?
This is the code I use. It
combines errors and output so if you get an error you still see it.
reads the data as it is produced so the buffer doesn't fill up.
doesn't remove new line only to add them back in.
.
private static String run(String... cmds) throws IOException {
ProcessBuilder pb = new ProcessBuilder(cmds);
pb.redirectErrorStream(true);
Process process = pb.start();
StringWriter sw = new StringWriter();
char[] chars = new char[1024];
try (Reader r = new InputStreamReader(process.getInputStream())) {
for (int len; (len = r.read(chars)) > 0; ) {
sw.write(chars, 0, len);
}
}
return sw.toString();
}
I want to get terminal history
So I did this
Runtime rt = Runtime.getRuntime();
pr = rt.exec("/bin/bash -c \"history -c\"");
pr.waitFor();
rt.exec("/usr/bin/xterm");
but there is problem with pr = rt.exec("/bin/bash -c \"history -c\""); , it's not clearing the previous history nither of xterm nor my normal terminal.
Also when I try to print the history it returns nothing (no errors)
p = Runtime.getRuntime().exec("/bin/bash -c \"history\"");
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("printing");
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
I also tried
String[] commands = new String[]{"/bin/sh","-c", "history -c" ,"xterm"};
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
} catch (IOException e1) {
e1.printStackTrace();
}
still not clearing history.
You can remove the history file yourself by getting the $HISTFILE environment variable. This will always get the correct history file for different shells. I believe the issue you're having is that the you may be using a different shell or have changed your history file location.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RemoveShellHistory {
public static void main(String[] args) {
RemoveShellHistory obj = new RemoveShellHistory();
final String shellPath = System.getenv("SHELL");
String shell = shellPath.substring(shellPath.lastIndexOf("/")+1, shellPath.length());
final String home = System.getenv("HOME");
String command = "rm -v " + home + "/." + shell + "_history";
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
Assuming that your java app runs by the same user possessing the .bash_history file:
To delete.
new File(System.getProperty("user.home"), ".bash_history").delete();
To clean (Handle the checked exception at your will).
FileWriter writer = new FileWriter(
new File(System.getProperty("user.home"), ".bash_history"));
writer.write("");
writer.close();
I have this piece of code
package Classes;
import java.io.*;
public class IpAdministrator {
public Boolean isActive(String ipAddress) {
boolean isActive = false;
String cmd;
String OS = System.getProperty("os.name");
System.out.println(OS);
String tmpfolder = System.getProperty("java.io.tmpdir");
System.out.println(tmpfolder);
//iptmp.deleteOnExit();
if (OS.equals("Linux")) {
cmd = "ping " + ipAddress + " -c 1";
} else {
cmd = "cmd /c ping " + ipAddress + " -n 1";
}
try {
String s = null;
Process p = Runtime.getRuntime().exec(cmd);
File iptmp = File.createTempFile("ipresult", ".txt", new File(tmpfolder));
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
s = s.toString();
BufferedWriter writer = new BufferedWriter(new FileWriter(iptmp));
writer.write(s);
}
} catch (Exception ex) {
System.out.println(ex.getMessage().toString());
}
return isActive;
}
}
I want to write the result from the command in the temporary file, I found something related in other questions in this site, and it seems to work fine, but when I run this, the file is created with some random numers (ie: ipresult540677216848957037.txt) and it's empty, I can't figure out why, I also read that it's something related to java 1.7, so that means that I can't fill the file with information, there something that I'm missing?
Every time you open a file for writing that way -- i.e., every time you execute this line:
BufferedWriter writer = new BufferedWriter(new FileWriter(iptmp));
the file is truncated to zero length. Furthermore, since you never explicitly call close() on the BufferedWriter, line you do write will never actually be flushed to the file. As a result, no data ever makes it to the disk.
To do this correctly, first, move the line above to before the loop, so it only executes once. Second, after the loop, include code like
if (writer != null)
writer.close();
Finally, note that your program is needlessly broken on Macs, which are neither Linux, nor do they use cmd.exe. Instead of the way you've written this, you test explicitly for Windows, and use the Windows command line if you find it; otherwise, assume something UNIX-like, and use the Linux version.
You need to close the writer
BufferedReader stdInput = new BufferedReader(new InputStreamReader(
p.getInputStream()));
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(iptmp));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
s = s.toString();
writer.write(s);
}
} finally {
if (writer != null) {
writer.close();
}
}
If you are using java 7
try (BufferedWriter writer = new BufferedWriter(new FileWriter(
iptmp));) {
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
s = s.toString();
writer.write(s);
}
}
I would like to run a windows command line command from java and return the result into java. Is this possible?
for example, I would like to do the following
Object returnValue = runOnCommandLine("wmic cpu get LoadPercentage");
//In this case, returnValue is the cpu load percent as a String
Edit: I was able to get this working
InputStream inputStream = new ProcessBuilder("wmic", "cpu", "get", "status").start().getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer);
String theString = writer.toString();
System.out.println("My string: " + theString);
Data you need is commandOutput.
String cmd = "wmic cpu get LoadPercentage";
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader stdin = new BufferedReader(
new InputStreamReader(p.getInputStream()));
StringBuilder commandOutput = new StringBuilder();
String line;
while ((line = stdin.readLine()) != null) {
commandOutput.append(line);
}
int exitValue = -1;
try {
exitValue = p.waitFor();
} catch (InterruptedException e) {
// do something here
}
You could do the following:
Process proc = Runtime.getRuntime().exec("net start");
InputStreamReader isr = new InputStreamReader(proc.getInputStream());
BufferedReader br = new BufferedReader(isr);
String temp = null;
while (( temp = br.readLine() ) != null)
System.out.println(temp);
Take a look into ProcessBuilder.
Below Java 1.5 Runtime.getRuntime().exec(...) was used.