Execute mysql command by Java + write out - java

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.

Related

Java how can I execute/run specific file by his path

I want to execute/run this file using Java.
The path is "/usr/local/studio.sh"
I tried:
public class Main {
public static void main(String[] args) {
String[] cmd = {"cd /usr/local","./studio.sh"};
try {
Process p = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
but it doesn't work. Is there another way?
You can use ProcessBuilder (see https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html) and set the working directory using directory(...) instead of cd command.
In the end something like this:
ProcessBuilder pb = new ProcessBuilder("/usr/bin/bash","/usr/local/studio.sh")
pb.directory(...);
pb.redirectErrorStream(true);
Process p = pb.start();
IOUtils.copy(p.getInputStream(), System.out);
p.waitFor();
This is work fine for me :
public static void main(String[] args) throws InterruptedException, IOException {
String[] cmd = {"/usr/local/android-studio/bin/studio.sh"};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
}
Thanks.
The Runtime API has a method to indicate the directory where you want to execute the method:
File folder = new File("/home/user/folder");
Process proc = Runtime.getRuntime().exec(command, null, folder);
The null in this case indicates: "no environment" defined.
Runtime API JavaDoc

When I pass ArrayList to ProcessBuilder I get the No such file or directory error

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();
}

cant run simple bash command in linux, permission denied

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

java Runtime.exec python not calling python script

I am trying to invoke a python script from java. The java compiles fine but the python script is not called.
public class javaToPython{
public static void main(String[] args) throws InterruptedException {
try {
Runtime runtime = Runtime.getRuntime();
Process process;
process = runtime.exec("python /home/james/YCSB/bin/pythonycsbcommand.py ");
process.waitFor();
}
catch (IOException ex) {
Logger.getLogger(javaToPython.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
python script:
import os
fo = open("/home/james/YCSB/bin/command.txt", "r+")
str = fo.read()
print "", str
fo.close()
os.system(str)
Edit:
I have tried using the process builder but again with the same results.
ProcessBuilder pb = new ProcessBuilder("python", "/home/james/YCSB/bin/script.py", "-m 2");
Process p = pb.start();
I have tried entering a path that does not exist but the java script still compiles.

Cannot keep gnome-terminal open

import java.io.*;
public class GnomeCommand {
public static void main(String args[]) throws IOException {
try {
Runtime r = Runtime.getRuntime();
String[] cmdArray = {"/usr/bin/gnome-terminal", "-e", "ps ax | grep gnome", " ; exec $SHELL"};
r.exec(cmdArray).waitFor();
} catch (InterruptedException ex){
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The problem is I cannot keep the command prompt open. It closes immediately. I also used "exec $SHELL" command but the result is same. I want to keep the terminal open after executing the command.
Your sub process ends when the command execution ends. In your case after ps and grep have finished executing your script will end.
Try with xterm with -hold option
xterm -e "ps ax | grep gnome" -hold

Categories