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

后端 未结 2 1388
走了就别回头了
走了就别回头了 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;
        }
    }
    

提交回复
热议问题