Why aren't my Windows batch files processing when Java executes them?

后端 未结 2 1386
走了就别回头了
走了就别回头了 2021-01-25 20:34

I have 2 folders, each containing dozens of batch files (*.bat).

The batch files containing text similar to either

del /f/q F:\\MEDIA\\IMAGE99         


        
相关标签:
2条回答
  • 2021-01-25 20:45

    Code of successful solution used, based on Ian Roberts' answer:

    Uses Apache Commons-IO

    package com.stackoverflow.windows;
    
    import java.io.File;
    import org.apache.commons.io.IOUtils;
    import org.apache.commons.io.output.NullOutputStream;
    
    public class Command {
    
        private Command() {}
    
        public static boolean batch(File file) {
        
            boolean handled = false;
            Process process = null;
            ProcessBuilder pb = new ProcessBuilder("cmd", "/c", file.getAbsolutePath());
            pb.redirectErrorStream(true);
        
            try {
    
                process = pb.start();
                IOUtils.copy(process.getInputStream(), new NullOutputStream());
                handled = process.waitFor() == 0;
                
            } catch (Exception ignore) {
            
                // Only throws an IOException we're trying to avoid anyway, 
                // and an expected InterruptedException 
                // handled will be false
            
            } finally {
    
                if (process != null) {
            
                    IOUtils.closeQuietly(process.getInputStream());
                }           
            }
                    
            return handled;
        }
    }
    
    0 讨论(0)
  • 2021-01-25 20:53

    now the output hangs at waitFor()

    When you start an external process from Java using Runtime.exec you must read any output that the process produces otherwise the process may block (source: JavaDocs for java.lang.Process).

    Use ProcessBuilder instead, and call redirectErrorStream to merge the standard output and error streams, then read all the content from process.getInputStream() until you reach EOF. Only then is it safe to call waitFor.

    ProcessBuilder will also help with the spaces issue, as you must split up the command line into individual words yourself

    ProcessBuilder pb = new ProcessBuilder("cmd", "/c", file.getAbsolutePath());
    
    0 讨论(0)
提交回复
热议问题