debugjavaMinor
Executing a file through a swing button
Viewed 0 times
executingfileswingbuttonthrough
Problem
I am making a Swing application for light local database management and I have the button
When that button is pressed this code is executed:
I basically have the three possible paths that xampp could be at and I go through them and check if the file exists and can be executed. If not then it prints the error that the file could not be found or is corrupt.
Do you have any tips for my code? Any better way of doing this and I'm especially concerned that my error handling is not that great.
Run XAMPP.When that button is pressed this code is executed:
private void jRunXAMPPButtonActionPerformed(java.awt.event.ActionEvent evt)
{
String[] paths = {"C:\\xampp\\xampp-control.exe",
"C:\\Program Files\\xampp\\xampp-control.exe",
"C:\\Program Files (x86)\\xampp\\xampp-control.exe"};
for (String path : paths) {
final File file = new File(path);
if (file.exists()) {
try {
Process p = Runtime.getRuntime().exec(file.getAbsolutePath());
} catch (IOException e) {
continue;
}
return;
}
}
Helper.printErrln("xampp-control.exe was not found or is corrupt!"); // Prints error in red
}I basically have the three possible paths that xampp could be at and I go through them and check if the file exists and can be executed. If not then it prints the error that the file could not be found or is corrupt.
Do you have any tips for my code? Any better way of doing this and I'm especially concerned that my error handling is not that great.
Solution
- Give your method a proper name. These auto-generated names are pure terror!
- You can import
ActionEventdirectly, no need to reference it with the entire package name.
- Your formatting is unusual at best, I'd call it bad. I know this is, for some reason, the preferred way to set braces in the Linux kernel code, but this is Java, not C.
- You are using hard-coded file paths. Absolute no-go. What if the user named his main partition
Dor installed xampp somewhere else – or is using Mac or Linux?
- Why are you storing the result in
Process pif you never use that variable?
- " // Prints error in red" is a comment that is both completely useless (why do I need to know this right then and there?) and will rot faster than you can imagine.
Context
StackExchange Code Review Q#48608, answer score: 5
Revisions (0)
No revisions yet.