I have a working sqoop command which imports data from oracle to hive.
When i am trying to run the sqoop command using the process builder API it is giving
java.io.IOException: error=2, No such file or directory
The same command works without any issues when executing it from the shell. Please let me know how to resolve this.
I also tried splitting the command into array of strings as well as list of strings. But, the two approaches did not work.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class SqoopTest {
static ProcessBuilder processBuilder = null;
static Process spawnProcess = null;
static int exitValue;
static int pid;
static List<String> commands;
public static void main(String[] args) {
runSqoop();
}
/*
* Executes the shell script with a series of sqoop commands.
*
*
*
* sqoop import -D mapred.child.java.opts='\-Djava.security.egd=file:/dev/../dev/urandom'
* --connect 'jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))'
* --username XXCSS_O --password "c******3" --split-by LINE_ITEM_ID -m 10
* --query "select LINE_ITEM_ID,LIST_PRICE,SERVICE_VALUE from XXCSS_KTN_REQ_LINE_DETAIL where \$CONDITIONS AND lid_date > to_date('2016-10-13 03:04:18','MM/dd/yyyy hh24:mi:ss') and lid_date <= to_date('2016-10-13 03:04:18','MM/dd/yyyy hh24:mi:ss')"
* --map-column-hive LINE_ITEM_ID=BIGINT,LIST_PRICE=BIGINT,SERVICE_VALUE=BIGINT
* --null-string '\\\\N' --null-non-string '\\\\N' --hcatalog-home
* /opt/mapr/hive/hive-1.2/hcatalog --hcatalog-table XXCSS_KTN_REQ_LINE_DETAIL --hcatalog-database frameworks_dataingestion
*
*/
public static void runSqoop() {
commands = new ArrayList<String>();
commands.add("sqoop import -D mapred.child.java.opts=\'\\-Djava.security.egd=file:/dev/../dev/urandom\' --connect \'jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))\' --username XXCSS_O --password \"c*****3\" --split-by LINE_ITEM_ID -m 10 --query \"select LINE_ITEM_ID,LIST_PRICE,SERVICE_VALUE from XXCSS_KTN_REQ_LINE_DETAIL where \\$CONDITIONS AND lid_date > to_date(\'2016-10-13 00:00:00\',\'yyyy-MM-dd hh24:mi:ss\') and lid_date <= to_date(\'2016-10-13 03:04:18\',\'yyyy-MM-dd hh24:mi:ss\')\" --map-column-hive LINE_ITEM_ID=BIGINT,LIST_PRICE=BIGINT,SERVICE_VALUE=BIGINT --null-string '\\\\N' --null-non-string '\\\\N' --hcatalog-home /opt/mapr/hive/hive-1.2/hcatalog --hcatalog-table XXCSS_KTN_REQ_LINE_DETAIL --hcatalog-database frameworks_dataingestion");
processBuilder = new ProcessBuilder(commands);
try {
System.out.println("Executing " + commands.toString());
spawnProcess = processBuilder.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(spawnProcess.getErrorStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.println(result);
try {
exitValue = spawnProcess.waitFor();
pid = getPID(spawnProcess);
System.out.println("The PID is " + pid);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("Process exited with the status :" + exitValue);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Retrieves the process id of the executed command.
*
* #param process the executed process
*
* #return PID
*/
public static int getPID(Process process) {
try {
Class<?> processImplClass = process.getClass();
Field fpid = processImplClass.getDeclaredField("pid");
if (!fpid.isAccessible()) {
fpid.setAccessible(true);
}
return fpid.getInt(process);
} catch (Exception e) {
System.out.println(e.getMessage());
return -1;
}
}
/*
* Retrieves the current java process id
*
* #return java process ID
*/
// #SuppressWarnings("restriction")
// public static int getCurrentJavaPID() {
// int jvmpid = 0;
// java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean();
// try {
// java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
// jvm.setAccessible(true);
// sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
// java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
// pid_method.setAccessible(true);
//
// jvmpid = (Integer) pid_method.invoke(mgmt);
// } catch (Exception e) {
// e.getMessage();
// }
// return jvmpid;
// }
}
Note: for security concerns i have replaced the ip addresses and passwords with dummy variables.
Tried passing the command as a string array. But, it doesnt recognize the JDBC Connection string
public static void runSqoop() {
String[] commands = {"sqoop","import","-D mapred.child.java.opts=\'\\-Djava.security.egd=file:/dev/../dev/urandom\'","--connect", "\'jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.370)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))\'","--username","XXCSS_O","--password","\"c***3\"", "--split-by","LINE_ITEM_ID","-m","10","--query","\"select LINE_ITEM_ID,LIST_PRICE,SERVICE_VALUE from XXCSS_KTN_REQ_LINE_DETAIL where \\$CONDITIONS AND lid_date > to_date(\'2016-10-13 00:00:00\',\'yyyy-MM-dd hh24:mi:ss\') and lid_date <= to_date(\'2016-10-13 03:04:18\',\'yyyy-MM-dd hh24:mi:ss\')\"","--null-string","'\\\\N'","--null-non-string","'\\\\N'","--hcatalog-home","/opt/mapr/hive/hive-1.2/hcatalog","--hcatalog-table","XXCSS_KTN_REQ_LINE_DETAIL","--hcatalog-database","frameworks_dataingestion"};
processBuilder = new ProcessBuilder(commands);
try {
System.out.println("Executing " + commands.toString());
spawnProcess = processBuilder.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(spawnProcess.getErrorStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.println(result);
try {
exitValue = spawnProcess.waitFor();
pid = getPID(spawnProcess);
System.out.println("The PID is " + pid);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("Process exited with the status :" + exitValue);
} catch (Exception e) {
e.printStackTrace();
}
}
Stack trace:
cat: /opt/mapr/zookeeper/zookeeperversion: No such file or directory
16/10/25 07:41:12 INFO sqoop.Sqoop: Running Sqoop version:
1.4.6-mapr-1609 16/10/25 07:41:12 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P
instead. 16/10/25 07:41:13 ERROR tool.BaseSqoopTool: Got error
creating database manager: java.io.IOException: No manager for connect
string:
'jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))'
at org.apache.sqoop.ConnFactory.getManager(ConnFactory.java:191)
at org.apache.sqoop.tool.BaseSqoopTool.init(BaseSqoopTool.java:256)
at org.apache.sqoop.tool.ImportTool.init(ImportTool.java:89)
at org.apache.sqoop.tool.ImportTool.run(ImportTool.java:593)
at org.apache.sqoop.Sqoop.run(Sqoop.java:143)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
at org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:179)
at org.apache.sqoop.Sqoop.runTool(Sqoop.java:218)
at org.apache.sqoop.Sqoop.runTool(Sqoop.java:227)
at org.apache.sqoop.Sqoop.main(Sqoop.java:236)
You have to provide commands and args separately as like below
Process p = new ProcessBuilder("myCommand", "myArg").start();
OR
ProcessBuilder pb =
new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.start();
Here is a example
Related
String executeCmd1 = "";
String executeCmd2 = "";
executeCmd1 = "C:/wamp64/bin/mysql/mysql5.7.14/bin/mysqldump -u "+dbUser+" -p"+dbPass+" "+dbName+" "+dbTable+" --where=id="+whereStatement+" --single-transaction --skip-lock-tables --no-create-info -r D:/backup.sql";
executeCmd2 = "C:/wamp64/bin/mysql/mysql5.7.14/bin/mysqldump -u "+dbUser+" -p"+dbPass+" "+dbName+" "+dbTable_1+" --where=course_id="+whereStatement+" --single-transaction --skip-lock-tables --no-create-info >> D:/backup.sql";
System.out.println(executeCmd1);
System.out.println(executeCmd2);
Process runtimeProcess =Runtime.getRuntime().exec(executeCmd1);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){
System.out.println("Backup taken successfully");
Process runtimeProcess1 =Runtime.getRuntime().exec(executeCmd2);
int processComplete1 = runtimeProcess.waitFor();
} else {
System.out.println("Could not take mysql backup");
}
while running the application first command line executes and backup is saved in file. Then running the second command but it's not working.
You could do this sort of thing with ProcessBuilder:
public class Dump {
public static void main(String[] args) {
try {
// (NB: All variables previously declared)
String[] executeCmd2 = {
"cmd.exe",
"/c",
"C:/wamp64/bin/mysql/mysql5.7.14/bin/mysqldump",
"-u",
dbUser,
"-p",
dbPass,
dbName,
dbTable_1,
"--where=course_id=",
whereStatement,
"--single-transaction",
"--skip-lock-tables",
"--no-create-info",
">> D:/backup.sql"
};
ProcessBuilder pb = new ProcessBuilder(executeCmd2);
pb.inheritIO();
pb.start();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
We are facing an issue where the below code is not able to open Microsoft Edge by running the command.
import java.io.IOException;
import java.io.InputStream;
public class ProcessTest {
private static final String NO_FRAME_MERGING_CMD_EDGE = "cmd.exe /c start microsoft-edge:";
private static final Object DOUBLE_QUOTE = "\"";
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
String url = "http://google.com";
url = new StringBuilder().append(DOUBLE_QUOTE).append(url).append(DOUBLE_QUOTE).toString();
System.out.println(NO_FRAME_MERGING_CMD_EDGE+ url);
Process process = rt.exec(NO_FRAME_MERGING_CMD_EDGE+ url);
printErrorlog(process);
}
public static void printErrorlog(Process process) {
try {
if (process != null && isProcessTerminated(process)) {
StringBuffer string_error = new StringBuffer();
InputStream errorStream = process.getErrorStream();
if (errorStream != null) {
int c = 0;
while ((c = errorStream.read()) != -1) {
string_error.append((char) c);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean isProcessTerminated (Process process) {
try {
process.exitValue();
} catch (IllegalThreadStateException itse) {
itse.printStackTrace();
return false;
}
return true;
}
}
In the logs we see
cmd.exe /c start microsoft-edge:"http://google.com"
java.lang.IllegalThreadStateException: process has not exited
at java.lang.ProcessImpl.exitValue(Native Method)
at ProcessTest1.isProcessTerminated(ProcessTest1.java:40)
at ProcessTest1.printErrorlog(ProcessTest1.java:22)
at ProcessTest1.main(ProcessTest1.java:16)
But the browser does not open.
When we run the command below in a bash file or on the command line, the windows is able to opening Edge. So I am not able to understand why it is not opening by Java.
cmd.exe /c start microsoft-edge:"http://google.com"
We are using jdk 6 to run the programm.
I want to run a PowerShell command for create user using Java on a remote windows machine, I am writing this code in eclipse.
And below is the output, tried every reference and forms to resolve this issue can someone help me with this.
The command works on PowerShell command line, but it is not working in Java.
public class PowerShellSession {
private static String subModule = "PowerShellSession";
String targetIpAddress;
String username;
String password;
public static Object connectPShellLock = new Object();
public PowerShellSession() {}
public void exec(String cmd, String credentials) {
//String ex = "New-LocalUser -Name \"User02\" -Description \"Description of this account.\" -NoPassword";
String ex = credentials +" Invoke-Command -ScriptBlock {" + cmd + "} -ComputerName " + targetIpAddress +" -Credential $mycred";
String[] args = new String[] { "powershell", ex};
try {
execRemote(args);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
String command = "Exit-PSSession";
String[] args = new String[] { "powershell", command};
try {
execRemote(args);
} catch (IOException e) {
e.printStackTrace();
}
}
private String getCredentials(String domain, String userName,
String password) throws IOException {
String creds = "$Username = '"+userName+"';$PlainPassword ='" + password
+ "'; $SecurePassword = ConvertTo-SecureString -AsPlainText $PlainPassword -Force;"
+ "$mycred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword;";
//creds += "$session = New-PSSession -ComputerName " + domain + " -Credential $mycred;";
String[] args = new String[] { "powershell", creds};
execRemote(args);
return creds;
}
private void execRemote(String[] arguments) throws IOException {
ProcessBuilder builder = new ProcessBuilder(arguments);
builder.redirectErrorStream(true);
Process process = builder.start();
doProcessIO(process);
}
// Do the IO for a passed process
private void doProcessIO(Process p) throws IOException {
p.getOutputStream().close();
String line;
System.out.println("Output:");
BufferedReader stdout = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
System.out.println("Error:");
BufferedReader stderr = new BufferedReader(new InputStreamReader(
p.getErrorStream()));
while ((line = stderr.readLine()) != null) {
System.out.println(line);
}
stderr.close();
System.out.println("Done");
}
public static void main(String[] args) throws IOException {
String ip_add = "192.168.193.101";
String user = "gs-259412";
String pass = "Windows412";
PowerShellSession psSession = new PowerShellSession();
String credentials = psSession.getCredentials(ip_add, user, pass);
psSession.targetIpAddress = ip_add;//;
String cmdd = "New-LocalUser -Name \"User02\" -Description \"Description of this account.\" -NoPassword";//"Get-Culture";
if(!credentials.equals("")) {
psSession.exec(cmdd, credentials);
System.out.println("Finished PowerShell remote session.");
}
psSession.close();
}
}
Output of this program :
Output:
Error:
Done
Output:
A positional parameter cannot be found that accepts argument 'of'.
+ CategoryInfo : InvalidArgument: (:) [New-LocalUser], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewLocalUserCommand
+ PSComputerName : 192.168.193.131
Error:
Done
Finished PowerShell remote session.
I tried this link also enter link description here
I wish to get the service name being used in the port. However, I am unable to. What I want to do is to check if a port is used. If it is used, then I want to get the service details on that port. How can I achieve this and what I am doing wrong?
public int checkPort(int port){
try {
InetAddress inetAddress = InetAddress.getLocalHost();
ss = new Socket(inetAddress.getHostAddress(), port);
if(ss.isBound()) {
System.out.println("Port " + port + " is being used by ");
Process p1 = Runtime.getRuntime().exec("grep -w " + port + " /etc/services");
p1.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
String line = reader.readLine();
while(line != null) {
System.out.println(line);
line = reader.readLine();
}
}
ss.close();
} catch (Exception e) {
System.out.println("Port " +port+ " is not being used");
}
return 0;
}
Results in
Port 139 is being used by
Port 139 is not being used
Well, assuming you are on Windows (it may or may not be different on other operating systems), you may be getting this exception.
Cannot run program "grep": CreateProcess error=2, The system cannot find the file specified
At least, that is what I got. You might be getting a totally different error. The main issue here is that there is one big try catch block with no e.printStackTrace() and it catches every exception. This means that when it goes wrong, there is no way to know why.
Hopefully this will work for you. Ironically you do not need a socket to test for services on a port so this may be an XY problem.
My solution to finding services on a port is the following.
SocketTester.java
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
/**
* An answer for Unable to get service details on port?
*
* #see Unable to get service details on port?
* #version 1.0
* #author Dan
*/
public class SocketTester {
/**
* This method checks whether a port is being used by any services.
* It will output any information to the system console.
*
* #param port The port to be checked for any services
*/
public static void checkPort(int port) {
TreeSet<String> pids = null;
List<Service> services = null;
pids = getPIDs(port);
if(pids != null) {
services = getServices(port, pids);
}
listInformation(port, services);
}
/**
* This method checks whether there are any PIDs on the specified port.
* If there are these are then returned.
*
* #param port The port to check for PIDs
* #return It returns a TreeSet containing any found PIDs on the specified port
*/
private static TreeSet<String> getPIDs(int port) {
TreeSet<String> returnVal = new TreeSet<String>();
ProcessBuilder pidProcessBuilder = new ProcessBuilder("cmd.exe", "/C", "netstat -ano | find \"" + port + "\"");
pidProcessBuilder.redirectErrorStream(true);
Process pidProcess = null;
try {
pidProcess = pidProcessBuilder.start();
} catch (IOException e) {
return null;
}
BufferedReader pidProcessOutputReader = new BufferedReader(new InputStreamReader(pidProcess.getInputStream()));
String outputLine = null;
try {
outputLine = pidProcessOutputReader.readLine();
} catch (IOException e) {
return null;
}
while (outputLine != null) {
List<String> outputLineParts = new ArrayList<String>(Arrays.asList(outputLine.split(" ")));
outputLineParts.removeAll(Arrays.asList(""));
//outputLineParts.get(1) is the local address. We don't want a foreign address to accidently be found
//outputLineParts.size() - 1 is the PID
if(outputLineParts.get(1).contains(":" + port) && !returnVal.contains(outputLineParts.get(outputLineParts.size() - 1))) {
returnVal.add(outputLineParts.get(outputLineParts.size() - 1));
}
try {
outputLine = pidProcessOutputReader.readLine();
} catch (IOException e) {
return null;
}
}
try {
pidProcess.waitFor();
} catch (InterruptedException e) {
return null;
}
return returnVal;
}
/**
* This method checks whether there are any services related to the PID.
* If there are these are then returned.
*
* #param port A reference to the PIDs port
* #param pids A list of PIDs found by getPIDs
* #return It returns a List containing any found services on the specified PIDs
*/
private static List<Service> getServices(int port, TreeSet<String> pids) {
List<Service> returnVal = new ArrayList<Service>();
for(String pid : pids) {
ProcessBuilder serviceProcessBuilder = new ProcessBuilder("cmd.exe", "/C", "tasklist /svc /FI \"PID eq " + pid + "\" | find \"" + pid + "\"");
serviceProcessBuilder.redirectErrorStream(true);
Process serviceProcess = null;
try {
serviceProcess = serviceProcessBuilder.start();
} catch (IOException e) {
return null;
}
BufferedReader serviceProcessOutputReader = new BufferedReader(new InputStreamReader(serviceProcess.getInputStream()));
String outputLine = null;
try {
outputLine = serviceProcessOutputReader.readLine();
} catch (IOException e) {
return null;
}
while(outputLine != null) {
List<String> outputLineParts = new ArrayList<String>(Arrays.asList(outputLine.split(" ")));
outputLineParts.removeAll(Arrays.asList(""));
//outputLineParts.get(0) is the service
returnVal.add(new Service(port, pid, outputLineParts.get(0)));
try {
outputLine = serviceProcessOutputReader.readLine();
} catch (IOException e) {
return null;
}
}
try {
serviceProcess.waitFor();
} catch (InterruptedException e) {
return null;
}
}
return returnVal;
}
/**
* This method lists the information found by checkPort
*
* #param port The port that has been checked for services
* #param servicesRunning The services found on the port
*/
private static void listInformation(int port, List<Service> servicesRunning) {
if(servicesRunning != null && servicesRunning.size() != 0) {
System.out.println("The following services are being run on port " + port);
for(Service service : servicesRunning) {
System.out.println("\t" + service.getService());
}
} else {
System.out.println("There are no services being run on port " + port);
}
}
public static void main(String[] args) {
final int portToCheck = 135;
checkPort(portToCheck);
}
}
Sevice.java
package socket;
/**
* An supplementary class to support SocketTester
*
* #see Unable to get service details on port?
* #version 1.0
* #author Dan
*/
public class Service {
private int port;
private String pid;
private String service;
public Service(int port, String pid, String service) {
this.port = port;
this.pid = pid;
this.service = service;
}
public int getPort() {
return port;
}
public String getPID() {
return pid;
}
public String getService() {
return service;
}
#Override
public String toString() {
return "Service \"" + "\" is being run on port " + port + " and has the PID " + pid;
}
}
Below method return me below path
Output - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
private String getPath() {
String mysqlpath = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(dbUrl, user, password);
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select ##datadir");
while (res.next()) {
mysqlpath = res.getString(1);
}
mysqlpath = mysqlpath.replace("\\Data", "\\bin").replace("\\", "\\\\");
System.out.println("Mysql path is :" + mysqlpath);
} catch (Exception ee) {
System.out.println(ee);
}
return mysqlpath;
}
Now i run below command to export mysql dump.
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec(batchCommand);
batchCommand - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\mysqldump" -h localhost --port 3306 -u root --password=root123 --add-drop-database -B accountingbook -r "E:\softwares\Tomcat_accountingBook\webapps\accountingbookaccountingbook-localhost-(02-08-2017).sql"
Exception - java.io.IOException: Cannot run program ""C:\ProgramData\MySQL\MySQL": CreateProcess error=2, The system cannot find the file specified
I also tried below, but same issue:-
1.) Process p = runtime.exec(batchCommand.split(" "));
2.) Adding double quotes like "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
Problem is it breaks as soon as it encounters space.
From the Exception, it looks like JVM is not able to find MYSQL executable file at the location given.
This can be due to "\" file separator. Try using "\\" to separate your paths. Then your path would be : "C:\\ProgramData\\MySQL\\MySQL.
I'v written one class this might help you click here
public class RuntimeExample {
private final String commandCode = "cmd /c";
private final Scanner scanner = new Scanner(System.in);
private Process process;
private BufferedReader reader;
private String input = "";
private final String defaultCode = "help";
public RuntimeExample() {
UserInput();
}
private void UserInput() {
System.out.println("Enter command (ex: ipconfig)");
input = scanner.nextLine();
if (input.isEmpty()) {
System.out.println("You didn't give any command please take a look at these available Commands." + "\n");
sendCommand(defaultCode);
} else {
sendCommand(input);
}
}
private void sendCommand(String command) {
try {
process = Runtime.getRuntime().exec(commandCode + " " + command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
showResult(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void showResult(String result) {
System.out.println(result + "\n");
}
public static void main(String[] args) {
new RuntimeExample();
}
}