Indexing backwards would protect you from finding existing file too early in cases like this:
You could add executable suffixes as you test for File.exists, to capture likes of ipconfig.exe from ipconfig.
You probably would NOT want to do this, but you could finally try executing the resulting string to test if it is an executable. This would be rather a dangerous thing to do with arbitrary input.
public class Example
{
public static void main(String[] args)
{
String[] samples = {
"C:\\windows\\system32\\notepad.exe bla.txt",
"C:\\WINDOWS\\system32\\ipconfig /all",
System.getProperty("user.home") + " foo bar"
};
for (String s: samples) {
File f = getFile(s, new String[]{"exe", "cmd"});
System.out.println(f);
// you probably don't want to do this
Process p = null;
try {
p = Runtime.getRuntime().exec(f.toString());
} catch (IOException e) {
System.err.println("Not executable: " + f);
} finally {
if (p != null) {
p.destroy();
}
}
}
}
public static File getFile(String cmd, String[] suffixes)
{
StringBuilder buffer = new StringBuilder(cmd);
while(true) {
File f = new File(buffer.toString());
if (f.exists()) {
return f;
} else {
for (String suffix: suffixes) {
f = new File(f.toString() + "." + suffix);
if (f.exists()) {
return f;
}
}
}
int start = buffer.lastIndexOf(" ");
if (start <= 0) {
break;
}
buffer.delete(start, buffer.length());
}
return null;
}
}