0

I would like to use the rar.exe path in Java. This is needed to unpack rar files from within my Java application without using a library.

I figured I'd require the user to add the program files folder for Winrar to the PATH system variable.

All I need to know now is how to get the full path to the rar.exe file.

What I've got now is this:

//Split all paths
String[] paths = System.getenv("Path").split(";");
for(String value : paths)
{
    if(value.endsWith("Winrar"))
        System.out.println(value);
}

However, there is no way of me knowing if the user installed Winrar to say C:\Programfiles\Winrarstuff. Is there a way to get the location of rar.exe, or do I have to manually scan every folder in the Path string for the location?

doublesharp
  • 24,192
  • 5
  • 46
  • 66
Christophe De Troyer
  • 2,660
  • 2
  • 26
  • 41

2 Answers2

1

You can use where on Windows Server 2003+ which is roughly equivalent to which in *nix, however you can get similar behavior for other windows environments using the code found here: https://stackoverflow.com/a/304441/1427161

Community
  • 1
  • 1
doublesharp
  • 24,192
  • 5
  • 46
  • 66
1

When the path to rar.exe is in the PATH environment variable, you can simply invoke rar.exe from any file location. That means you can also call it via Runtime.exec(...). If the return code is other than 0, the process cannot be started, e.g. because Winrar is not installed:

public static boolean checkRar() {
    Process proc = Runtime.getRuntime().exec("cmd /c rar.exe");
    try (BufferedReader reader =
            new BufferedReader(new InputStreamReader(proc.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            // parse line e.g. to get version number
        }
    }
    return (proc.waitFor() == 0);
}
isnot2bad
  • 22,602
  • 2
  • 27
  • 43
  • My first code snippet was simply executing "rar.exe" does NOT respect the PATH environment. Instead "cmd /c rar.exe" must be called (windows only!) and it is required to read the input from the process, otherwise it will not terminate. – isnot2bad Nov 16 '13 at 15:37
  • Why would you execute `rar` through `cmd` here? – Joey Nov 16 '13 at 15:39
  • @Joey if you don't do it that way, the PATH environment variable is ignored, so you'd have to specify the full path to rar.exe. – isnot2bad Nov 16 '13 at 15:51
  • So there is no portable way of executing programs in the `PATH` in Java? That sounds odd. – Joey Nov 16 '13 at 21:48
  • Yes, but on the other hand, rar.exe is not portable too, so one will have to port the code anyway. – isnot2bad Nov 16 '13 at 22:20