I want launch a batch file with JAVA. So I create a shortcut to this file and config Run as Administrator. I tested the batch file and it run success. But when, I run it with java, the batch file don't run with Administrator and the request is denied.
In java source, I try to call a shortcut of cmd.exe with shortcut configed Run as Administrator. And java source open the commandline with Administrator success.
Please help me.
Here my code:
package testfp;
import java.io.*;
public class RunCommand {
String command,result;
public RunCommand(String command) {
this.command = command;
run();
System.out.println(this.result);
}
public void run() {
try
{
Process process = Runtime.getRuntime().exec("cmd /c start C:\\Users\\minhlc\\Desktop\\test\\CMD");
// Fail to open with Administrator
// Process process = Runtime.getRuntime().exec("cmd /c start C:\\Users\\minhlc\\Desktop\\test\\start_apache");
// process.destroy();
// Process process = Runtime.getRuntime().exec("cmd /c start");
// kill_process();
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
try {
while ((line = br.readLine()) != null) {
this.result = this.result + "\n" + line;
}
} finally {
// br.close();
};
} catch (IOException e)
{
e.printStackTrace();
}
}
public void kill_process()
{
try {
Runtime.getRuntime().exec("taskkill /f /im cmd.exe") ;
} catch (Exception e) {
e.printStackTrace();
}
}
public String get_result() {
return result;
}
}
Thank for reading.
You need to run the java process with an administration privilege.
Open command line with "Run as administrator" and then
java -jar you_app.jar
I have the following test code:
public class TestProcessBuilder {
public static void main(String args[]) {
String imageLocation = "/home/john/image";
String installCommand = "java -jar install.jar -install /home/john/install.properties";
ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File(imageLocation));
pb.command(Arrays.asList(installCommand.split("\\+s")));
try {
pb.start();
} catch(Exception e) {
e.printStackTrace();
System.out.println("Failed to run command");
}
}
This gives me an error:
Cannot run program "java -jar install.jar -install /home/john/install.properties" (in directory "/home/john/"): error=2, No such file or directory
Do I have to create a separate list and then manually add each tokenized item to it. I thought this should work...
You should make sure that path to your java folder is exported. You can then use something similar to this:
public static void main(String[] args) {
String command = "java";
String parameters = "-jar install.jar -install /home/john/install.properties";
ProcessBuilder pb = new ProcessBuilder(command, parameters);
try {
pb.start();
} catch (IOException e) {
e.printStackTrace();
}
}
Depends of your need, but you could use also this if you want to pass whole command in one string:
try {
Runtime.getRuntime().exec("java -jar install.jar -install /home/john/install.properties");
} catch (IOException e) {
e.printStackTrace();
}
I'm trying to run a simple command from console using this
public void execute(File file, String... command){
Process p = null;
ProcessBuilder builder = new ProcessBuilder("ls");
builder.directory(file.getAbsoluteFile());
builder.redirectErrorStream(true);
try {
p = builder.start();
} catch (IOException e) {
LOGGER.error("", e);
}
}
but it kept saying that I cant run ls, permission denied. Is there any missing step here?
Thanks
You should use pass the commands and the flags to the constructor of the ProcessBuilder separately (as per the docs):
public void execute(File file, String... command) {
ProcessBuilder builder = new ProcessBuilder("ls", "-l");
builder.directory(file.getAbsoluteFile());
builder.redirectErrorStream(true);
try {
Process p = builder.start();
} catch (IOException e) {
LOGGER.error("", e);
}
}
It seems you want to execute command, though. To do this, you can pass command to ProcessBuilder's constructor.
public void execute(File file, String... command) {
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(file.getAbsoluteFile());
builder.redirectErrorStream(true);
try {
Process p = builder.start();
} catch (IOException e) {
LOGGER.error("", e);
}
}
Here's the ideone to the working code
You'll notice that when I run it with "ls -l", there's a problem executing the command. This is because the first argument is treated as the command to be executed and the remaining arguments are treated as flags.
To change permissions of bash commands in EC2 instances, execute
chmod u+x /home/admin/ec2-api-tools-*/bin/*
This depends on a couple of things:
1) The user that runs java (your process will be ran as that user)
2) The directory where your JAR or class resides.
Also make sure that your account has proper permissions if the java user is not the same as the user you are logged in as.
ProcessBuilder builder = new ProcessBuilder("ls -l");
There is no process named "ls -l". You want to use the process named "ls" with the arguments "-l", for that you need:
ProcessBuilder builder = new ProcessBuilder("ls", "-l");
I made this code to move a folder then hardlink it to it's original destination. The problem it works fully when I'm just trying it from eclipse but when I make it into it's own self executing jar it wont create the hardlink but it will move the folder. The code runs a command line and then enters the commands. I dont know ehy the move command works and not the other one. Please help.
(Mklink command)
import java.io.*;
import javax.swing.JOptionPane;
public class The_Cloud_Setup {
public static void main(String[] args) throws IOException
{
try {
String command = "c:\\cmd.exe";
Runtime.getRuntime().exec(command);
}
catch (IOException e){
JOptionPane.showMessageDialog(null , e.getMessage(), "End Result", 2);
System.err.println(e.getMessage());
}
String[] StringMove = { "cmd.exe", "/c", "move"+" "+"\"C:/Users/%username%/Documents/My Games/Terraria/Players\""+" "+"\"C:/Users/%username%/Google Drive/Players\""};
String[] StringMklink = {"cmd.exe", "/c", "mklink"+" "+"/d"+" "+"\"C:/Users/%username%/Documents/My Games/Terraria/Players\""+" "+"\"C:/Users/%username%/Google Drive/Players\""};
Process ProcessMove = Runtime.getRuntime().exec(StringMove);
Process ProcessMklink = Runtime.getRuntime().exec(StringMklink);
BufferedReader VarMove = new BufferedReader(new InputStreamReader(ProcessMove.getInputStream()));
BufferedReader VarMklink = new BufferedReader(new InputStreamReader(ProcessMklink.getInputStream()));
String temp = "";
while ((temp = VarMove.readLine()) != null) {
System.out.println(temp);
}
VarMove.close();
VarMklink.close();
}
}
Most likely, when you are running natively, the move command has not completed before your program attempts to execute the mklink command. You can't make a link where there is an existing folder.
I want to create diff of two files. I tried searching for code in Java that does it, but didnt find any simple code/ utility code for this. Hence, I thought if I can somehow run linux diff/sdiff command from my java code and make it return a file that stores the diff then it would be great.
Suppose there are two files fileA and fileB. I should be able to store their diff in a file called fileDiff through my java code. Then fetching data from fileDiff would be no big deal.
You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.
For example, here's a complete program that will showcase how to do it:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class testprog {
public static void main(String args[]) {
String s;
Process p;
try {
p = Runtime.getRuntime().exec("ls -aF");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {}
}
}
When compiled and run, it outputs:
line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0
as expected.
You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).
If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder.
You can also write a shell script file and invoke that file from the java code. as shown below
{
Process proc = Runtime.getRuntime().exec("./your_script.sh");
proc.waitFor();
}
Write the linux commands in the script file, once the execution is over you can read the diff file in Java.
The advantage with this approach is you can change the commands with out changing java code.
You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec
Process p = Runtime.getRuntime().exec("diff fileA fileB");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
try to use unix4j. it s about a library in java to run linux command. for instance if you got a command like:
cat test.txt | grep "Tuesday" | sed "s/kilogram/kg/g" | sort
in this program will become:
Unix4j.cat("test.txt").grep("Tuesday").sed("s/kilogram/kg/g").sort();
You can call run-time commands from java for both Windows and Linux.
import java.io.*;
public class Test{
public static void main(String[] args)
{
try
{
Process process = Runtime.getRuntime().exec("pwd"); // for Linux
//Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line=reader.readLine())!=null)
{
System.out.println(line);
}
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
process.destroy();
}
}
}
Hope it Helps.. :)
Runtime run = Runtime.getRuntime();
//The best possible I found is to construct a command which you want to execute
//as a string and use that in exec. If the batch file takes command line arguments
//the command can be constructed a array of strings and pass the array as input to
//the exec method. The command can also be passed externally as input to the method.
Process p = null;
String cmd = "ls";
try {
p = run.exec(cmd);
p.getErrorStream();
p.waitFor();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
}finally{
p.destroy();
}
The suggested solutions could be optimized using commons.io, handling the error stream, and using Exceptions. I would suggest to wrap like this for use in Java 8 or later:
public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException {
try {
return execute(command, 0, null, false);
} catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
return execute(command, 0, null, true);
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
Process process = new ProcessBuilder().command("bash", "-c", command).start();
if(timeUnit != null) {
if(process.waitFor(timeout, timeUnit)) {
if(process.exitValue() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
} else {
if(destroyOnTimeout) process.destroy();
throw new ExecutionTimeoutException("Execution timed out: " + command);
}
} else {
if(process.waitFor() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
}
}
public static class ExecutionFailedException extends Exception {
private static final long serialVersionUID = 1951044996696304510L;
private final int exitCode;
private final List<String> errorOutput;
public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) {
super(message);
this.exitCode = exitCode;
this.errorOutput = errorOutput;
}
public int getExitCode() {
return this.exitCode;
}
public List<String> getErrorOutput() {
return this.errorOutput;
}
}
public static class ExecutionTimeoutException extends Exception {
private static final long serialVersionUID = 4428595769718054862L;
public ExecutionTimeoutException(final String message) {
super(message);
}
}
if the opening in windows
try {
//chm file address
String chmFile = System.getProperty("user.dir") + "/chm/sample.chm";
Desktop.getDesktop().open(new File(chmFile));
} catch (IOException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
{
JOptionPane.showMessageDialog(null, "Terjadi Kesalahan", "Error", JOptionPane.WARNING_MESSAGE);
}
}
ProcessBuilder processBuilder = new ProcessBuilder();
// -- Linux --
// Run a shell command
processBuilder.command("bash", "-c", "ls /home/kk/");
// Run a shell script
//processBuilder.command("path/to/hello.sh");
// -- Windows --
// Run a command
//processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\kk");
// Run a bat file
//processBuilder.command("C:\\Users\\kk\\hello.bat");
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output);
System.exit(0);
} else {
//abnormal...
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}