I have a c++ program (.exe) that runs in the command line. You don't open it with cmd, it just opens the command prompt on its own and uses it as a menu. I also have a login system built in Java. My issue is, I'm trying to open my C++ program in the Java program, and it just isn't working. Here is the latest iteration of the relevant code:
btnLaunchMyProgram.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
File file1 = new File("C://Users//" + System.getProperty("user.name") + "//Desktop//My Program//myprogram.exe");
if(!file1.exists()) {
try {
HttpDownloadUtility.downloadFile("https://www.example.com/downloads/MyProgram.exe", "C://Users//" + System.getProperty("user.name") + "//Desktop//My Program//");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Process p = Runtime.getRuntime().exec(new String[] {"cmd.exe", "\"" + "C://Users//" + System.getProperty("user.name") + "//Desktop//My Program//MyProgram.exe" + "\""});
} catch (IOException e) {
e.printStackTrace();
}
}
});
In order to get rid of a few concerns you might have
- I have also tried the following, which runs my program in the background, but doesn't open the command prompt:
Process p = Runtime.getRuntime().exec(new String[] {"C://Users//" + System.getProperty("user.name") + "//Desktop//My Program//MyProgram.exe"});
and also:
Process p = Runtime.getRuntime().exec(new String[] {"cmd.exe", "C://Users//" + System.getProperty("user.name") + "//Desktop//My Program//MyProgram.exe"});
None of these work.
Just to be clear about what I need to happen:
1. I press the button (btnLaunchMyProgram)
2. It opens the exe and, by extension, the command prompt / console.
3. That's basically all it needs to do.
Related
I'm trying to run the jhipster import-jdl command from a java program as show below.
public boolean generate(String foldername, String filename) {
Runtime rt = Runtime.getRuntime();
try {
IPath root = ResourcesPlugin.getWorkspace().getRoot().getLocation();
Process proc = rt.exec(new String[] { "cmd", "/K",
"cd " + root + "\\" + foldername + " && jhipster import-jdl " + filename });
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
But the entity files are not getting created.
But if I open the command prompt in the folder specified in the code and run the same command as shown below manually, the entity files are generated.
cd C:\GitClone\work && jhipster import-jdl swaggertest.jh
I'm new to these things and have no idea on where am I going wrong. Please help me with the same.
I'm trying to compile C source file with gcc using ProcessBuilder. I managed to make it running but there is no output file.
Here is my code (based on this answer) :
public void compileWithGccNoCmd(Path sourcePath) throws IOException {
String sourcePathString = sourcePath.toString();
String outputPathString = sourcePath.getParent().toString() + "\\" + Files.getNameWithoutExtension(sourcePath.toString());
try {
ProcessBuilder pb = new ProcessBuilder("gcc", "-fprofile-arcs -ftest-coverage -o " + outputPathString, sourcePathString);
pb.directory(sourcePath.getParent().toFile()); // this was added later
Process compile = pb.start();
compile.waitFor();
if (compile.exitValue() == -1) {
// if error
System.out.print("COMPILE ERROR");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
My first thought that it has something to do with the working directory so I add pb.directory() but the output file still not there.
Since I can't find any solution to this, I tried another way by running gcc with cmd. I set the working directory to make sure the output files on the right place. This is the alternative code (based on this answer):
public void compileWithGcc(Path sourcePath) throws IOException {
String sourcePathString = sourcePath.toString();
String outputPathString = sourcePath.getParent().toString() + "\\" + Files.getNameWithoutExtension(sourcePath.toString());
ProcessBuilder pb;
try {
pb = new ProcessBuilder("cmd", "/C", "gcc " + sourcePathString + " -o " + outputPathString + " -fprofile-arcs -ftest-coverage");
pb.directory(sourcePath.getParent().toFile());
Process p = pb.start();
p.waitFor();
int x = p.exitValue();
} catch (Exception ex) {
ex.printStackTrace();
}
}
For some reason it works! Why is this happened? I'm pretty sure both is running gcc with the same parameter
This line:
ProcessBuilder pb = new ProcessBuilder("gcc", "-fprofile-arcs -ftest-coverage -o " + outputPathString, sourcePathString)
needs to look like this:
ProcessBuilder pb = new ProcessBuilder("gcc", "-fprofile-arcs", "-ftest-coverage", "-o", outputPathString, sourcePathString)
What you are doing with the first line is passing two arguments to gcc, one of which is "-fprofile-arcs -ftest-coverage -o " + outputPathString, instead of passing the five arguments of my edited line. gcc won't understand that.
When you use cmd like you did, it parses the command that you gave it and passes the arguments correctly, that's why it works.
I'm trying to make a function that reboot the javafx application, On windows 10 works perfectly but on Windows 7 it doesn't, I search for this solution and it was perfect, then I test it on Windows 10 and nothing, the app just turn off. Also I test it watching for an exception inside the log file and it doesn't throw any Exception.
Something specific must be made in order to work also on windows 7? maybe a different approach? Thanks.
this is the code:
//Restart app the current Java application, with parameter you can pass a Runnable to do before restart app, null if not
public static void restartApplication(Runnable runBeforeRestart) throws IOException {
try {
/**
* Sun property pointing the main class and its arguments.
* Might not be defined on non Hotspot VM implementations.
*/
final String SUN_JAVA_COMMAND = "sun.java.command";
// java binary
String java = System.getProperty("java.home") + "/bin/java";
// vm arguments
List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
// if it's the agent argument : we ignore it otherwise the
// address of the old application and the new one will be in conflict
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
// init the command to execute, add the vm args
final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
// program main and program arguments
String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
// program main is a jar
if (mainCommand[0].endsWith(".jar")) {
// if it's a jar, add -jar mainJar
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
// else it's a .class, add the classpath and mainClass
cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
}
// finally add program arguments
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
// execute the command in a shutdown hook, to be sure that all the
// resources have been disposed before restarting the application
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
logToFile.log(e, "info", "The application fail to restart, applying the command");
}
}
});
// execute some custom code before restarting
if (runBeforeRestart!= null) {
runBeforeRestart.run();
}
// Wait for 2 seconds before restart
//TimeUnit.SECONDS.sleep(2);
// exit
System.exit(0);
} catch (Exception e) {
// something went wrong
logToFile.log(e, "info", "The application fail to restart generally");
}
}
Update: Searching for other approach I found out a solution, It's test it on both Windows OS and works
here it's the code:
//Restart app the current Java application, with parameter you can pass a Runnable to do before restart app, null if not
public static void restartApplication(Runnable runBeforeRestart, Integer TimeToWaitToExecuteTask) throws IOException {
try {
// execute some custom code before restarting
if (runBeforeRestart != null) {
// Wait for 2 seconds before restart if null
if (TimeToWaitToExecuteTask != null) {
TimeUnit.SECONDS.sleep(TimeToWaitToExecuteTask);
} else {
TimeUnit.SECONDS.sleep(2);
}
runBeforeRestart.run();
}
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
final File currentJar = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
/* is it a jar file? */
if (!currentJar.getName().endsWith(".jar"))
return;
/* Build command: java -jar application.jar */
final ArrayList<String> command = new ArrayList<String>();
command.add(javaBin);
command.add("-jar");
command.add(currentJar.getPath());
final ProcessBuilder builder = new ProcessBuilder(command);
builder.start();
System.exit(0);
} catch (Exception e) {
// something went wrong
logToFile.log(e, "info", "The application fail to restart generally");
}
}
I have a executable program made on C++ (cf.exe) that takes parameters from a few text files (.txt), performs some calculations, and creates a file with the results (results.txt). This program needs no interaction. Once executed, when the calculations are done, it's automatically closed.
Then, I have other program made on Java, which contains a button that executes the cf.exe. When the button is pressed the following method is called:
public void executeExternalProgram(){
String filePath = "C++" + File.separator + "cf.exe";
try {
System.out.println("Executing C++ exe...");
Process p = Runtime.getRuntime().exec(filePath);;
} catch (Exception e) {
e.printStackTrace();
}
}
I don't get any error, but the cf.exe is not being executed when I press the button. When I execute manually the cf.exe, the results file is correctly created. Furthermore, I've tried to copy other programs, such as notepad.exe, to the same folder and execute it through Java without any problem. Can anyone see why it's not working?
I found that changing the command given to the process makes it work correctly. The change is the following:
Process p = Runtime.getRuntime().exec("cmd /c start "+ filePath);
Then, the updated code for the method called when the button is pushed:
public void executeExternalProgram(){
String filePath = "C++" + File.separator + "cf.exe";
try {
System.out.println("Executing C++ exe...");
Process p = Runtime.getRuntime().exec("cmd /c start "+ filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
I have to open (or execute in the background) a cmd window out of my java application. It did this before and it worked totally fine:
public String getEnvVar(String envVarName) throws Exception {
String varName = "%" + envVarName + "%";
Process process = Runtime.getRuntime().exec(
new String[]{"cmd.exe", "/C", "echo " + varName}
);
BufferedReader input = new BufferedReader(
new InputStreamReader(process.getInputStream())
);
varName = input.readLine();
process.destroy();
...
My problem is: I have a different instance of a different class and tried to open a cmd window just the way it is done in the code above:
private void execute() {
try {
String batchData = batchContent();
Process process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "/C", batchData});
new File(sourceFile).delete();
new File(sourceFolder).delete();
process.destroy();
} catch (IOException ie) {
}
}
But this doesn't work...I used google to figure out why, couldn't find a real reason for this.
Even
Process process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "cd c:\\temp"});
does not change into the temp folder (which i created beforehand for testing reasons)
What's wrong?
EDIT//
I now tried:
private void upload() {
try {
//Process process = Runtime.getRuntime().exec(batchDataFile);
//Process process = Runtime.getRuntime().exec("cmd.exe /C " + batchDataFile);
Process process = Runtime.getRuntime().exec("cmd.exe /C " + "\"" + batchDataFile + "\"");
//new File(sourceCodeFile).delete();
//new File(batchDataFile).delete();
//new File(sourceCodeFolder).delete();
process.destroy();
} catch (IOException ie) {
ie.printStackTrace();
}
}
I additionally tried to run the generated batch skript without the Java app, it works as intended