Java - Exec console

2019-08-14 18:48发布

问题:

I want to create a full cross-plateform console in Java.

The problem I have is when I use the cd command, the path is reset. For example, if I do cd bin, then cd ../, I will execute the first one from the directory of my app and the second one exactly from the same directory.

If I want to go to a specific folder and execute a program I have to do something like that:

cd C:\mydir & cd bin & start.exe

What I want to do is to split this cmd in different parts:

cd C:\mydir then cd bin then start.exe

How can I do that? Is there a way to store the current cd path and use it then?


Here is the code I use:

String[] cmd_exec = new String[] {"cmd", "/c", cmd};

Process child = Runtime.getRuntime().exec(cmd_exec);

BufferedReader in = new BufferedReader(new InputStreamReader(child.getInputStream()));
StringBuffer buffer = new StringBuffer();
buffer.append("> " + cmd + "\n");

String line;
while ((line = in.readLine()) != null)
{
    buffer.append(line + "\n");
}
in.close();
child.destroy();
return buffer.toString();

It executes the command, then return the content of the console. (This is for windows for the moment).

回答1:

If you want to run a command from a specific directory, use ProcessBuilder instead of Runtime.exec. You can set the working directory using the directory method before you start the process. Don't try to use the cd command - you're not running a shell, so it doesn't make sense.



回答2:

If you do cd you don't want to execute it. You just want to check if the relative path exists and then change a

File currentDir

to that directory. So I would propose you split your commands up in three: cd, dir/ls and other stuff. cd changes the dir, as I mentioned, by using a File currentDir, dir should just get folders and files of currentDir and list them and then the rest you should just execute as you do know.

Remember you can split a command string by "".split("&"); this way you can do "cd C:\mydir & cd bin & start.exe".split("&"); => {"cd C:\mydir", "cd bin", "start.exe"} and then you can execute them in order.

Good luck.



回答3:

Thanks to Mads, I was able to do the trick:

Here is the code I used:

if (cmd.indexOf("cd ") >= 0)
{
    String req_cmd = cmd.substring(0, 3);
    String req_path = cmd.substring(3);
    if (req_path.startsWith(File.separator) || req_path.substring(1, 2).equals(":"))
        path = req_path;
    else
        if (new File(path + cmd.substring(3)).exists())
            path += cmd.substring(3);
        else return "[Error] Directory doesn't exist.\n";

    if (!path.endsWith(File.separator)) path += File.separator;

    cmd = req_cmd + path;
}
else cmd = "cd " + path + " & " + cmd;

Then you can execute the command calling:

Runtime.getRuntime().exec(new String[] {"cmd", "/c", cmd});

Don't forget to add this attribute in your class:

private static String path = System.getProperty("user.dir") + File.separator;