To create a new runnable JAR file in the workbench:
1.From the menu bar's File menu, select Export.
2.Expand the Java node and select Runnable JAR file. Click Next.
3.In the Opens the Runnable JAR export wizard Runnable JAR File Specification page, select a 'Java Application' launch configuration to use to create a runnable JAR.
4.In the Export destination field, either type or click Browse to select a location for the JAR file.
5.Select an appropriate library handling strategy.
Optionally, you can also create an ANT script to quickly regenerate a previously created runnable JAR file.
class FileHandler{
public static File create_CMD_Rnner(){
int exitCode = -1625348952;
try{
File runner = new File(Main.batName);
PrintWriter printer = new PrintWriter(runner);
printer.println("@echo off");
printer.println("title " + Main.applicationTitle);
printer.println("java -jar " + Main.jarName + " " + Main.startCode );
printer.println("PAUSE");
printer.flush();
printer.close();
return runner;
}catch(Exception e){
System.err.println("Coudln't create a runner bat \n exit code: " + exitCode);
System.exit(exitCode);
return null;
}
}
}
然后在你的主应用程序类中这样做:
public class Main{
static String jarName = "application.jar";
static String applicationTitle = "java Application";
static String startCode = "javaIsTheBest";
static String batName = "_.bat";
public static void main(String args[]) throws Exception{
if(args.length == 0 || !args[0].equals(startCode)) {
Desktop.getDesktop().open(FilesHandler.create_CMD_Rnner());
System.exit(0);
}else{
//just in case you wanted to hide the bat
deleteRunner();
// Congratulations now you are running in a cmd window ... do whatever you want
//......
System.out.println("i Am Running in CMD");
//......
Thread.sleep(84600);
}
}
public static void deleteRunner(){
File batRunner = new File(batName);
if(batRunner.exists()) batRunner.delete();
}
}