CMD.exe command in java does not end

I am trying to use cmd.exe to search for a file in a specific directory, and then display the path in a java program and write it to a file. The problem is that the process never ends.

Here is my code:

String[] str = new String[] { "cmd.exe ", "cd c:\\",
                        " dir /b /s documents", "2>&1" };

            Runtime rt = Runtime.getRuntime();
            try{

                Process p = rt.exec(str);
                InputStream is =p.getInputStream();
                InputStreamReader in = new InputStreamReader(is);


                StringBuffer sb = new StringBuffer();
                BufferedReader buff = new BufferedReader(in);
                String line = buff.readLine();
                while( line != null )
                {
                    sb.append(line + "\n");
                    line = buff.readLine();
                }
                System.out.println( sb );
                File f = new File("test.txt");
                FileOutputStream fos = new FileOutputStream(f);
                fos.write(sb.toString().getBytes());
                fos.close();

            }catch( Exception ex )
            {
                ex.printStackTrace();
            }
+3
source share
4 answers

Try

cmd /c

instead of simple

cmd

Link

+1
source

Runtime.execdoes not work. You cannot pass multiple commands like this to cmd.exe.

Runtime.execallows you to execute one process with a list of arguments. It does not provide any "shell" operations (for example, 2>&1). You must do this I / O redirection yourself using I / O streams.

main.

"Runtime.exec( String [] {" cmd.exe "," /c "," dir "," C:\\"});

, , java.io.File, .

+1

Java ? !

0

You must use the start command in addition to the cmd.exe process with the / C or / K switch BEFORE the start command. Example: to convert the Windows command interpreter to the bash console (from mingw prroject), you must call the exec method of the Runtime class using the command "C: \ Windows \ System32 \ cmd.exe / C start C: \ mingw \ msys \ 1.0 \ bin \ bash.exe "(I use an external command, not an internal one, because it is more meaningful, but you can use an internal command such as DIR, etc.).

0
source

Source: https://habr.com/ru/post/1731401/


All Articles