create bat file - Java Native OS

Java examples for Native OS:Shell Command

Description

create bat file

Demo Code


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{
    public static void main(String[] argv) throws Exception{
        String cmd = "java2s.com";
        System.out.println(createBatFile(cmd));
    }// w ww . ja v  a 2 s  .  c o  m
    
    public static String createBatFile(String... cmd) {
        if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1) {
            String path = System.getProperty("user.dir") + File.separator
                    + "temp" + DateUtil.getCurrentDateTimeAsId() + ".bat";
            FileUtil.createFile(path);
            StringBuffer content = new StringBuffer();
            for (int i = 0; i < cmd.length; i++) {
                content.append(cmd[i] + "\r\n");
            }
            FileUtil.writeFile(path, content.toString());
            return "\"" + path + "\"";
        } else {
            String path = System.getProperty("user.dir") + File.separator
                    + "temp.sh";
            FileUtil.createFile(path);
            StringBuffer content = new StringBuffer();
            content.append("#!/bin/sh").append("\n");
            for (int i = 0; i < cmd.length; i++) {
                content.append(cmd[i] + "\r\n");
            }
            FileUtil.writeFile(path, content.toString());
            return path;
        }
    }
}

Related Tutorials