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

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!

Related

How do I run a python 2.7 code from my Java?

I have a Java Swing class from which I want my Java application to run a local python program after clicking a button. The following code does not run the executable python I have created.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
Process process =
Runtime.getRuntime().exec("C:\\Users\\User\\Desktop\\hello.exe");
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have even tried running the python script file using:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Process p= Runtime.getRuntime().exec("C:\\Python27\\python.exe \"C:\\Users\\User\\Desktop\\hello.py\"");
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have no errors yet neither does the job. I can run applications like notepad etc using the same syntax, however I cant with python and I'm unsure how to resolve this.
P.s. I do have Python 2.7 PATH in my environment variable. Also, the above are just the methods for the action performed by the buttons. I have all the other methods and main class in my full program.
Process p= Runtime.getRuntime().exec("cmd /c /K \"C:\\Python27\\python.exe C:\\Users\\User\\Desktop\\hello.py\"");
do this way.. call the Python from cmd
I tried this simple example & it worked for me...
Files : CallPython.java & hello.py
CallPython.java
import java.util.*;
import java.io.*;
class CallPython{
public static void main(String args[]){
try{
Process proc= Runtime.getRuntime().exec("python hello.py");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
/*
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
*/
stdInput.lines().forEach(System.out::println);
}
catch(IOException e){
System.err.println("Error occured while executing an external process...");
}
}
}
hello.py
print('Hello...from python script');
Output:
Hello...from python script

Backup a mysql [xampp] database in java

So I am still learning programming, I am creating a simple application that can backup a database but the problem is when I click the button for backup, nothing happens, it does not even display the "can't create backup". I am using xampp, in case that is relevant. I have zero idea as to why is it is not working, and I am really curios what is the reason behind it, any help will be greatly appreciated.
...
String path = null;
String filename;
//choose where to backup
private void jButtonLocationActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
String date = new SimpleDateFormat("MM-dd-yyy").format(new Date());
try {
File f = fc.getSelectedFile();
path = f.getAbsolutePath();
path = path.replace('\\', '/');
path = path+"_"+date+".sql";
jTextField1.setText(path);
} catch (Exception e) {
e.printStackTrace();
}
}
//backup
private void jButtonBackUpActionPerformed(java.awt.event.ActionEvent evt) {
Process p = null;
try{
Runtime runtime = Runtime.getRuntime();
p=runtime.exec("C:/xampp/mysq/bin/mysqldump -u root --add-drop-database -B capstone -r "+path);
int processComplete = p.waitFor();
if (processComplete==0) {
jLabel1.setText("Backup Created Success!");
} else {
jLabel1.setText("Can't create backup.");
}
} catch (Exception e) {
}
}
You use a try-catch block in the jButtonBackUpActionPerformed, but the catch statement is empty. Therefore, if an exception is raised for whatever reason, no file would be written and you would get no output. You can try to use e.printStackTrace() like in the catch statement of the other button for debugging.
I found the underlying problem, thanks to stan. It was a typo problem, instead of "mysql", I have put "mysq" thank you guys!
java.io.IOException: Cannot run program "C:/xampp/mysq/bin/mysqldump.exe": CreateProcess error=2, The system cannot find the file specified
this will run any shell script on Linux server. Test it on windows ... shoud work too
public static int executeExternalScript(String path) throws InterruptedException, IOException {
ProcessBuilder procBuilder = new ProcessBuilder(path);
procBuilder.redirectErrorStream(true);
Process process = procBuilder.start();
BufferedReader brStdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while((line = brStdout.readLine()) != null) { logger.info(line); }
int exitVal = process.waitFor();
brStdout.close();
return exitVal;}

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

Running CMD commands from JAVA

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.

Run.reg file with Java

I am trying to run reg files with Java. I tried this with no luck:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class RegEdit {
public static void main(String[] args) throws IOException {
// Desktop.getDesktop().open(new File("ihindi.reg"));
String[] cmd = {"regedit", "ihindi.reg"};
Process p = Runtime.getRuntime().exec(cmd);
try {
p.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ihindi.reg
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer\Control Panel]
"HomePage"=dword:00000001
When I run it, it doesn't make anything and errors. Where am I doing wrong ?
I think you would need to add the "/s" statement in between, your process probably got disturb while you're writing the data into the regedit.
I was in the exactly same situation as yours, no error, but it just couldn't write into the regedit. the "/s" did the job.
try{
// silence all the process without prompting the dialog box to ask if user wanna proceed.
String[] cmd = { "regedit.exe", "/s", regFilePath};
Process process = Runtime.getRuntime().exec(cmd);
process.waitFor();
}catch (InterruptedException e){
System.out.println(e);
}
There are all sorts of problems with this. The following line:
String[] cmd = {"regedit", "ihindi.reg"};
should pass the full path to the ihindi.reg file, not just the file name.
Also,
It is possible that a dialog box is preventing that waitFor() call from ever returning.
You should call regedit with the /s switch to silence those dialog boxes.
Also, you might consider using a ProcessBuilder like so:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class RegEdit {
public static void main(String[] args) throws IOException {
// Desktop.getDesktop().open(new File("ihindi.reg"));
//you will need to figure this out
String ihindiPath = getIhindiPath();
ProcessBuilder processBuilder = new ProcessBuilder("regedit", "/s", ihindiPath)
try {
processBuilder.start().waitFor();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I think the problem is your paths, with your current code *.reg would have to be in the same directory as the jar file. You can however set the working directory explictly when usong ProcessBuilder:
ProcessBuilder pb = new ProcessBuilder("regedit", "myreg.reg");
pb.directory("c:/");//thus our file should be located in c:\myreg.reg
Process p = pb.start();
This can achieved through Process Builder in JAVA. Please consider the following example for this:
ProcessBuilder processBuilder = new ProcessBuilder("regedit", "reg_file_to_run.reg");
Process processToExecute = processBuilder.start();
And then you can optionally wait for the completion of process execution with this line:
processToExecute.waitFor();
Note: If command in your registry file asks for confirmation prompts while making changes in registry entries, you can perform it silently as well with '/s' option. Like this:
ProcessBuilder processBuilder = new ProcessBuilder("regedit", "/s", "reg_file_to_run.reg");
Withthis command would be executed silently without any confirmation prompt.

Categories