Java - Exec console - java

I want to create a full cross-plateform console in Java.
The problem I have is when I use the cd command, the path is reset. For example, if I do cd bin, then cd ../, I will execute the first one from the directory of my app and the second one exactly from the same directory.
If I want to go to a specific folder and execute a program I have to do something like that:
cd C:\mydir & cd bin & start.exe
What I want to do is to split this cmd in different parts:
cd C:\mydir then cd bin then start.exe
How can I do that? Is there a way to store the current cd path and use it then?
Here is the code I use:
String[] cmd_exec = new String[] {"cmd", "/c", cmd};
Process child = Runtime.getRuntime().exec(cmd_exec);
BufferedReader in = new BufferedReader(new InputStreamReader(child.getInputStream()));
StringBuffer buffer = new StringBuffer();
buffer.append("> " + cmd + "\n");
String line;
while ((line = in.readLine()) != null)
{
buffer.append(line + "\n");
}
in.close();
child.destroy();
return buffer.toString();
It executes the command, then return the content of the console. (This is for windows for the moment).

If you want to run a command from a specific directory, use ProcessBuilder instead of Runtime.exec. You can set the working directory using the directory method before you start the process. Don't try to use the cd command - you're not running a shell, so it doesn't make sense.

If you do cd you don't want to execute it. You just want to check if the relative path exists and then change a
File currentDir
to that directory. So I would propose you split your commands up in three: cd, dir/ls and other stuff. cd changes the dir, as I mentioned, by using a File currentDir, dir should just get folders and files of currentDir and list them and then the rest you should just execute as you do know.
Remember you can split a command string by "".split("&"); this way you can do "cd C:\mydir & cd bin & start.exe".split("&"); => {"cd C:\mydir", "cd bin", "start.exe"} and then you can execute them in order.
Good luck.

Thanks to Mads, I was able to do the trick:
Here is the code I used:
if (cmd.indexOf("cd ") >= 0)
{
String req_cmd = cmd.substring(0, 3);
String req_path = cmd.substring(3);
if (req_path.startsWith(File.separator) || req_path.substring(1, 2).equals(":"))
path = req_path;
else
if (new File(path + cmd.substring(3)).exists())
path += cmd.substring(3);
else return "[Error] Directory doesn't exist.\n";
if (!path.endsWith(File.separator)) path += File.separator;
cmd = req_cmd + path;
}
else cmd = "cd " + path + " & " + cmd;
Then you can execute the command calling:
Runtime.getRuntime().exec(new String[] {"cmd", "/c", cmd});
Don't forget to add this attribute in your class:
private static String path = System.getProperty("user.dir") + File.separator;

Related

How to run multiple cmd commands through Java?

I have a simple GUI which selects an executable and a batch file. Clicking "run" should launch a command line instance, then run the executable given the selected batch. However, hiccups seem to show up at different points. This is the relevant code snippet:
String[] commands = {"cmd.exe", "/c", "C:\\Xilinx\\14.7\\ISE_DS\\settings64.bat && cd /d ",
"\"" + simFile.getParent() + "\"", " && ping localhost && ",
"\"" + jTextField1.getText() + "\"", " -tclbatch \"" + jTextField2.getText() + "\""};
ProcessBuilder simBuilder = new ProcessBuilder(commands);
simBuilder.redirectErrorStream(true);
Process simulation = simBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(simulation.getInputStream()));
String line;
while (true) {
line = reader.readLine();
if (line == null)
break;
System.out.println(line);
}
I chose to create a process through a ProcessBuilder rather than "Runtime.getRuntime().exec" because having the command and arguments as a String array is more readable and manageable. I took a look through the documentation of Runtime, Process, and ProcessBuilder. I also searched for similar questions, the following being the closest: Run cmd commands through Java. However, I'm still having issues getting all commands to run properly, if it all. First point: The program successfully executes the commands until "ping", which I placed to determine where the issue occurs. I get the cmd output in the console through the BufferedReader just fine. However, the next command, which should run the executable indicated by "jTextField1.getText()", gives an error of "The filename, directory name, or volume label syntax is incorrect" although I made sure the path is within escaped double quotes to account for spaces. Is it something in my syntax? Something to do with where the double ampersands are placed? Does every separate command with its argument need to be its own string in the array? I tried that and different things, but it always seems to result in an error.
You should check that your path names are correct, and try the cmd as one parameter value not as comma separated after cmd.exe /c. This will ensure the arguments are passed to CMD correctly as a single argument for the CMD shell to handle:
import java.nio.file.Files
System.out.println("Files.isDirectory(simFile.getParent())="+Files.isDirectory(simFile.getParent()));
System.out.println("Files.isExecutable(jTextField1.getText())="+Files.isExecutable(Path.of(jTextField1.getText())));
String cmd = "C:\\Xilinx\\14.7\\ISE_DS\\settings64.bat && cd /d "+
"\"" + simFile.getParent() + "\" && ping localhost && "+
"\"" + jTextField1.getText() + "\" -tclbatch \"" + jTextField2.getText() + "\"";
String[] commands = {"cmd.exe", "/c", cmd};

JavaFX program cannot run python script after it's deployed

I have written a JavaFX program that runs a python script that uses google console search api to get data. It works fine before I deploy it as a standalone program (.exe). After I install the program it runs fine until I click the button that runs the script; it does nothing.
After the button is clicked it succesfully checks if the python is installed or not, after that the problem occurs when it tries the run the script. I have specified the path like this, "./src/com/fortunamaritime/" and I think this might be the problem.
private static final String ANALYTICS_PATH ="./src/com/fortunamaritime/";
inside the method
//set up the command and parameter
String[] cmd = new String[3];
cmd[0] = "python";
cmd[1] = "analytics.py";
cmd[2] = "https://fortunamaritime.com.tr";
String command = cmd[0] + " " + cmd[1] + " " + cmd[2] + " " +
startDate + " " + endDate;
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "cd " + new
File(ANALYTICS_PATH).getAbsolutePath() + " && " + command);
builder.redirectErrorStream(true);
Process p = builder.start();
I have redirected console output to a .txt file to see what was happening and there's only one line that said "system cannot find the path specified".
I have switched from absolute path to relative path and it produced this error:
The filename, directory name, or volume label syntax is incorrect.
I also printed this line to console
this.getClass().getResource("/com/fortunamaritime/analytics.py")
and the result is:
jar:file:/D:/IdeaProjects/FortunaWebTracker/out/artifacts/FortunaWebTracker/FortunaWebTracker.jar!/com/fortunamaritime/analytics.py
Is it possible to access the inside of the jar file and run the script from there via cmd through stripping parts of this URL?
Copy the script to a (maybe temporary) file and run it from that file.
You can get the script as InputStream with Main.class.getResourceAsStream(String resc) (relative to main) or Main.class.getClassLoader().getResourceAsStream(String resc) (relative to root)
You may use java.nio.file.Files#createTempFile(String,String and delete that file on exit.
You can also copy the script into the user home or relative to the exe (and don't delete it).
For example, you could do this:
File dir=new File("./resc");
if(!dir.exists()) {
dir.mkdirs();
}
File analyticsFile=new File(dir,"analytics.py");
if(!analyticsFile.exists()) {
/*
* alternative:
* this.getClass().getResourceAsStream("com/fortunamaritime/analytics.py")
*/
try(InputStream analyticsIn = this.getClass().getClassLoader().getResourceAsStream("analytics.py")){
Files.copy(analyticsIn, analyticsFile.toPath());
}
}
/*
* alternative: String command=String.join(" ",new String[]{"python",analyticsFile.getAbsolutePath(),"https://fortunamaritime.com.tr"});
*/
String command="python "+analyticsFile.getAbsolutePath()+" https://fortunamaritime.com.tr";
/*
* alternative (without error redirection): Process p=Runtime.getRuntime().exec(command);
*/
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process p=builder.start();
I have solved my problem.
Here's the code sample first, explanation will follow;
String path = new
File(Main.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
path=path.substring(0,path.length()-21);
// set up the command and parameter
String[] cmd = new String[3];
cmd[0] = "python";
cmd[1] = "analytics.py";
cmd[2] = "https://fortunamaritime.com.tr";
String command0="jar xf FortunaWebTracker.jar" +
"com/fortunamaritime/analytics.pycom/fortunamaritime/client_secrets.json" +
" com/fortunamaritime/webmasters.dat";
String command1 = cmd[0] + " " + cmd[1] + " " + cmd[2] + " " + startDate + " " +
endDate;
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "cd " + path + " && " +
command0+"&&"+"cd "+path+"\\com\\fortunamaritime"+" && "+command1);
builder.redirectErrorStream(true);
Process p = builder.start();
My first mistake was to use absolute path, and the second problem arose when I got the path I wanted via:
File(Main.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
//Jar's name is 21 characters long, minus that and I get the directory path
path=path.substring(0,path.length()-21);
The second problem was unpacking elements inside the jar so I used this command in cmd:
jar xf FortunaWebTracker.jar
com/fortunamaritime/analytics.py
com/fortunamaritime/client_secrets.json
com/fortunamaritime/webmasters.dat
then I could get it to work.

Run bat file from different disk with java

Im trying to run a bat from C:/abc/def/coolBat.bat but my java workspace is in D:/
I've tried with :
String cmd = "cmd /c /start C:/abc/def/coolBat.bat";
Runtime.getRuntime().exec(cmd);
But didn't work, so I tried this
String[] command = { "cmd.exe", "/C", "C:/abc/def/coolBat.bat" };
Runtime.getRuntime().exec(cmd);
didnt work either. Tried this too
Executor exec = new DefaultExecutor();
exec.setWorkingDirectory(new File("C:/abc/def"));
CommandLine cl = new CommandLine("coolBat.bat");
int exitvalue = exec.execute(cl);
Says it cant find the file.
Tried something like this too:
Runtime.getRuntime().exec("cmd cd /d C:/abc/def/ && coolBat.bat");
And nothing. The weird thing is that this command:
cd /d C:/abc/def/ && coolBat.bat
Works when i do it in cmd. Its worth saying that the bat file copies some files to another directory, all inside C:/
EDITED N°1
CD C:\abc\def\MN
copy almn + ctmn + bamn C:\abc\def\mn_sf.txt
CD C:\abc\def\ME
copy alme + ctme + bame C:\abc\def\me_sf.txt
CD C:\abc\def\
if exist MN.txt del MN.txt
if exist ME.txt del ME.txt
if exist JUZ.txt del JUZ.txt
if exist FUNC.txt del FUNC.txt
if exist AHO.txt del AHO.txt
CD C:\
Allow MS Windows to use the associated application to run your batch file (or any other application):
Required Imports:
import java.awt.Desktop;
Here is code you can try:
String filePath = "C:/abc/def/coolBat.bat";
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File(filePath);
Desktop.getDesktop().open(myFile);
}
catch (IOException | IllegalArgumentException ex) {
System.err.println("Either there is no application found "
+ "which is associatd with\nthe file you want to work with or the "
+ "file doesn't exist!\n\n" + filePath);
}
}
Well I finally got it to work, just had to change my workspace to C:/
Apparently the problem was that it couldn't change from D:/ to C:/ to execute. I ran the same commands I tried before and there was no problem.
Guess the question remains, why it couldn't change from D:/ to C:/ when running commands from Java.
Thanks to everyone for the help
The Java version could work as:
String[] command = {"cmd.exe", "/C", "Start", "/D", "c:\\abc\\def", "c:\\abc\\def\\coolBat.bat"};
Process process = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = errReader.readLine()) != null) {
System.out.println(line);
}
System.out.flush();
int retCode = process.waitFor();
System.out.println("Return code: " + retCode);
Try this:
String[] command = { "cmd.exe", "/C", "C: && C:/abc/def/coolBat.bat" };

"Program Files" command intern not found CMD

I use java to excute a command line to create a database, i get an error when i excute this piece of code:
private final String POSTGRES_PATH = "\"C:\\Program Files\\PostgreSQL\\9.3\\bin\\psql.exe\"";
private final String DATA_BASE = "bd_name";
private void creerDataBase() {
String command = this.POSTGRES_PATH + " -U postgres -d postgres -c \"CREATE DATABASE " + this.DATA_BASE + "\"";
System.out.println("command = " + command);
String creerBDD = executerCommande(command);
System.out.println("Resultat : " + creerBDD);
}
public String executerCommande(String command) {
String line;
String resultat = "";
try {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (true) {
line = r.readLine();
if (line == null) {
break;
}
resultat += line + "\n";
}
} catch (Exception e) {
System.out.println("Exception = " + e.getMessage());
}
return resultat;
}
I get this result:
command = "C:\Program Files PostgreSQL\9.3\bin\psql.exe"\ -U postgres -d postgres -c "CREATE DATABASE bd_name"
and this error:
'C:\Program' n'est pas reconnu en tant que commande interne
This mean that Program is not an intern command.
but when i excute this command in CMD it work fine?
Is there any way to Build this Path because the ProcessBuilder not recognize C:\Program Files
Thanks for #Aaron his idea helps me so i solved this problem using this:
private final String POSTGRES_PATH = "C:\\PROGRA~1\\PostgreSQL\\9.3\\bin\\psql.exe";
this C:\\PROGRA~1 inteed of this: C:\\Program Files
A possible solution would be to remove the path (with spaces) from your constant field and use the directory method:
Sets this process builder's working directory. Subprocesses subsequently started by this object's start() method will use this as their working directory. The argument may be null -- this means to use the working directory of the current Java process, usually the directory named by the system property user.dir, as the working directory of the child process.
Changing your code to:
private final String POSTGRES_DIR = "C:\\Program Files\\PostgreSQL\\9.3\\bin\\"
private final String POSTGRES_COMMAND = "psql.exe";
....
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command).directory(new File(POSTGRES_DIR));
.....
Don't run cmd.exe if you want to run a separate binary program.
cmd.exe is for scripts like *.cmd or *.bat
With cmd.exe you have to pass your command as an argument of CMD, and you should manage all OS-specific pitfalls like long paths with whitespaces, quotes inside qoutes etc.
Instead, you had better run psql itself.
The ProcessBuilder takes a command and all the arguments as a list of separate strings. And ProcessBuilder is clever enough to do all the necessary magic with quotes and whitespaces by itself.
And take attention to the list of arguments - shells separate arguments by whitespaces, while psql might recognize the sequence of strings as a single argument.
We may assume that -U postgress is a single argument for psql, but for shell (cmd.exe in our case) these are two separate arguments - -U and postgress, so we should pass them to the ProcessBuilder separately
So the better way to run psql is to run it directly, something like that:
new ProcessBuilder("C:\\Program Files\\PostgreSQL\\9.3\\bin\\psql.exe",
"-U", "postgres",
"-d", "postgres",
"-c", "\"CREATE DATABASE " + this.DATA_BASE + "\"");
What you could try is instead of the space between program and files is %20 or \s.
So like:
command = "C:\\Program%20Files\\PostgreSQL\\9.3\\bin\\psql.exe"
or
command = "C:\\Program\sFiles\\PostgreSQL\\9.3\\bin\\psql.exe"
I hope one of them works for you, please let me know
EDIT: use double \ to get it to recognize the \

How to change the Directory from command prompt using Java code

public void VerifyFiles(File dir) throws IOException{
File[] files = dir.listFiles();
for (File file : files) {
//Check if directory
if (file.isDirectory()) {
//Recursively call file list function on the new directory
VerifyFiles(file);
} else {
try {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \" C:\\Users\\e843778\\Documents\\NetBeansProjects\\EncryptedFiles\" && C:\\Program Files\\PGP Corporation\\PGP Desktop");
builder.redirectErrorStream(true);
Process p = builder.start();
Runtime rt = Runtime.getRuntime();
String query2 = "cmd /c pgpnetshare -v " + "\"" + file + "\"";
Process proc = rt.exec(query2);
proc.waitFor();
System.out.println("Executing for: " + file);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
String s1 ="";
while ((line = in.readLine()) != null)
{
System.out.println(line);
if(line.contains("All files and folders are encrypted"))
s1+=line;
}
System.out.println(s1);
}
I have to run a pgpnetshare command for all the files in a given directory using command prompt. For that, first i need to change my current directory to other directory. But i was not able to change the directory with the below code. I have checked all the previous answered questions in Stackoverflow.com. But none of them helped me.Please verify the code and please let me know if it needs any corrections. Thanks in advance!!.
That should work:
Process process=Runtime.getRuntime().exec(query2,
null, new File("directory path"));
From the documentation:
Process exec(String[] cmdarray, String[] envp, File dir)
Executes the specified command and arguments in a separate process with the specified environment and working directory.
You can always create a .bat file and execute that instead.
you should use using file.getAbsolutePath()
like
String query2 = "cmd /c pgpnetshare -v " + "\"" + file.getAbsolutePath() + "\"";

Categories

Resources