cant run simple bash command in linux, permission denied - java

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");

Related

When I open CMD from Java, I cannot change the Directory

I have a problem with my Java program where I have a button that opens the command prompt and opens a batch file to run a series of commands. To do this, I need to change directory.
Here is my code:
private void CommandPromptButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
new java.lang.ProcessBuilder("cmd.exe").start();
java.lang.Runtime.getRuntime().exec(new String[]{
//I need to change the directory in command prompt and I do not want to use escape
"cmd.exe","/c","start","cd C:\Users\Faz"
});
} catch (IOException ex) {
Logger.getLogger(TMISGUIInstallerPage.class.getName()).log(Level.SEVERE, null, ex);
}
}
Any suggestions and advice are appreciated.
The following code should work
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"C:\\Users\\Faz\" && dir");
You could change the directory in the ProcessBuilder using the ProcessBuilder#directory() and then start the process. Here is a sample code:
ProcessBuilder start = new ProcessBuilder("cmd.exe", "/c", "start");
start.directory(new File("C:\\Users"));
start.start();
Upvoted Aukta's answer, it should solve your problem.
But as you asked:
To do this, I need to change directory.
Actually with ProcessBuilder and its directory(File directory), we can easily set the working directory. Here is a simple demo to list all files in a specified directory to show you how it can be used.
public static void main(String... args) {
ProcessBuilder processBuilder = new ProcessBuilder("ls"); // pass in your command and options;
processBuilder.directory(new File("/home")); // specify you directory here;
try {
Process process = processBuilder.start();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
The output:
gitlab-runner
hearen
ubuntu
Thanks for all of your help and suggestions. I have finally found an answer. I forgot to add that I tried using Java runtime but that does not run all commands. I have found that if I add another quotation mark, I can change the directory.
private void CommandPromptButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
new java.lang.ProcessBuilder("cmd.exe").start();
java.lang.Runtime.getRuntime().exec(new String[]{
//I need to change the directory in command prompt and I do not want to use escape
"cmd.exe","/c","start","cd C:\"Users\"Faz"
});
} catch (IOException ex) {
Logger.getLogger(TMISGUIInstallerPage.class.getName()).log(Level.SEVERE, null, ex);
}
}
Thank you for all of your help. Probs submit some more questions later. Cheers!

Could not load main class when compiled and executed with Runtime.exec()

I have the following code to run three executions :
public static void main(String[] args) throws InterruptedException, IOException
{
String filepath1 = "cmd /c gradlew jmhJar";
String filepath2 = "cmd /c java -jar path/to/the/file/filename.jar -rf csv -rff path/to/save/file1.csv -wi 3 -i 5 -f 2";
String filepath4 = "cmd /c javac path/to/the/file/ParserHash.java";/*Code to compile is parserHash.java*/
String filepath3 = "cmd /c java path/to/the/compiled/class/ParserHash "C:/Users/msek/Desktop/trial/result/file1.csv C:/Users/msek/Desktop/trial/result/file2.csv C:/Users/msek/Desktop/trial/result/file3.csv";
try
{
runProcess(filepath1);
runProcess(filepath2);
System.out.println("Sucessfully written into file1.csv");
runProcess(filepath4);
System.out.println("Compilation Over");
runProcess(filepath3);
System.out.println("Program Sucessfully Executed");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void runProcess(String processString)
{
try
{
final Process p = Runtime.getRuntime().exec(processString);
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
}
catch (Exception x)
{
x.printStackTrace();
}
}
If I compile the java file going to that particular directory and compile its compiling successfully and on running it, it executes successfully. But if I pass it like "cmd /c path/to/java/file/file.java" its getting compiled but when I execute it, I get an error stating that could not find or load mainclass eventhough class file is present.
I have looked various links on this which suggested buid process, but that didn't work.
I just want to know where I'm going wrong and how to compile, execute a java file by passing multiple arguments using Runtime.exec()..
java path/to/the/compiled/class/ParserHash
If you're having trouble with an exec() you should:
Try the command from a command line yourself. It will fail the same way in this case.
Look up the syntax of the command. In this case you will learn that the argument to the java command is not a path but a class name, fully qualified, i.e. including the package name. With dots.

How to close application (stanford: it is a folder consists many programs.) in CMD after I open it? java ProcessBuilder Runtime

Please know that stanford is not exe. it is a folder consists many programs
I open the cmd.exe by using following statement:
public static void runStanfordCMD() throws IOException{
List<String> cmds = Arrays.asList("cmd.exe", "/C", "start", "java", "-mx4g", "-cp", "*", "edu.stanford.nlp.pipeline.StanfordCoreNLPServer");
ProcessBuilder builder = new ProcessBuilder(cmds);
builder.directory(new File("D:/Desktop/stanford-corenlp-full-2015-12-09"));
Process proc = builder.start();
}
so how to close the cmd.exe after I finished some process?
by using ProcessBuilder or Runtime?
If using ProcessBuilder how to write the statement according to my case?
how to write the statement to the Runtime according to my case?
public static void closeStanfordCMD() throws IOException{
try {
Runtime.getRuntime().exec("command.exe /C" + "Your command"); // how to write the statement?
} catch (Exception e) {
e.printStackTrace();
}
}
The method
Runtime.getRuntime().exec
returns an object of Process.
Process has a method destroy() which kills the process you're running.
So what you need is to store the Process object returned by the exec method and call destroy() on it when you want to kill the process.
Also you can call waitFor() method to wait for the process to stop (Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated).
To make it clear, try this code (or modify for your needs):
try {
Process p = Runtime.getRuntime().exec("java -mx4g -cp * D:/Desktop/stanford-corenlp-full-2015-12-09/edu.stanford.nlp.pipeline.StanfordCoreNLPServer");
p.waitFor();
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
// how to write the statement?
if you want to close command prompt:
Runtime.getRuntime().exec("taskkill /IM " + "cmd.exe");
if you want to close stanford.exe:
Runtime.getRuntime().exec("taskkill /IM " + "stanford.exe");

Execute mysql command by Java + write out

I need to execute mysql command by Java and write out the result.
But, only empty file created.
Execution environment is MacOS 10.11.2.
public class Main {
public static void main(String[] args) {
String[] cmd = new String[]{"/bin/sh", "-c", "mysql", "-u", "root", "-ppassword", "databaseName"};
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.redirectInput(ProcessBuilder.Redirect.from(new File("sample.sql")));
builder.redirectOutput(new File("result.tsv"));
try {
Process p = builder.start();
p.waitFor();
System.out.println(builder.redirectInput());
} catch (IOException | InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
sample.sql select * from sample;
when the main method executed, displayed redirect to read from file "sample.sql" on console.
And, result.tsv is still empty.
If I input mysql -u root -ppassword -D sql2xlsx < sample.sql > result.tsv into Terminal.app directly,
result.tsv is not empty, and writed expected results.

Not able to execute command from java

I want to execute below command from java program .
java -jar jarfile.jar -dir C:/MyDirectory -out C:/MyDirectory/example.html
I tried following , but its opening cmd prompt , but it not executing next command
Runtime rt = Runtime.getRuntime();
try {
rt.exec(new String[] { "cmd.exe", "/c", "start" , "java -jar exampleJar.jar -dir C:\\MyDirectory -out C:\\MyDirectory\\exampleHtml.html" });
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am using the following piece of code and its working perfect,ProcessBuilder is used to create operating system processes and each instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. To create new subprocesses with the same instance start() method can be called repeatedly.
public void execute(String[] code){
try{
ProcessBuilder pb=new ProcessBuilder(code);
pb.redirectErrorStream(true);
Process process = pb.start();
BufferedReader inStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while(inStreamReader.readLine() != null){
System.out.println(inStreamReader.readLine());
}
} catch (IOException e) {
System.out.println(e.toString());
e.printStackTrace();
log.error(e.getMessage());
}
}

Categories