Question

I've created a java GUI that executes batch files in order to easily and seamlessly command a serial com port device.

try {
Process p = Runtime.getRuntime().exec("toggleLed.bat");
    } catch(Exception e) {
      e.printStackTrace();
    }

This code executes the following .bat file:

@ECHO OFF
ECHO A >COM1
EXIT

This code sends the letter "A" over com port 1 and the device interprets it as a command and turns on the LED, works perfectly. The only problem is, I want to be able to change the COM port via the java GUI. I have a "jSpinner" but I'm not sure how to get this to edit the com port value in the batch file.

Question: How do I get my java GUI to edit a batch file value?

PS: I'm using batch files to communicate over serial because I have tried numerous libraries such as RXTX but none of them work well/are too complicated.

Was it helpful?

Solution

Don't use a batchfile for a single command:

String command="cmd /C \"ECHO A >COM"+portNum+"\""; 

This translates to cmd /C "ECHO A>COM#"

and call it with:

Process p = Runtime.getRuntime().exec(command);

If you need multiple commands separate them with & inside the command line, such as cmd /C "FOO&BAR --baz"

Note that the quotes that are part of the command line are escaped with a backslash.

However, I strongly recommend you take the time to learn and use a library as it is far more portable.

Libraries can operate on multiple OSs(not just Windows) with some minimal changes, and definitely not a complete rewrite of your application. They can be carried around as jars with your project and put into the classpath, similar to what you're doing with your batch file now, but actually cross-compatible.

Libraries may take a few extra minutes to set up in the project but can be carried around with it and put in the classpath via a custom classloader or, more simply, the -cp parameter to the java command. You can also edit the manifest file to add the jar to the classpath.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top