• 0

[JAVA] Runtime.getRuntime().exec() help


Question

Hey, i'm writing a simple program that uses a JFileChooser to select a .java file, copies it to the C:/java directory, then compiles it into a .jar file. I'm having problems launching command.bat and running the commands. My code currently looks like: (My mainClass.txt is already in the target directory)

import javax.swing.JFileChooser;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;

public class JavaCompile {
	private String[] cmd;
	private String name;
	private JFileChooser fc;
	private File fin;
	private String path;



	public static void main(String[] args){
		JavaCompile jc = new JavaCompile();
	}



	public JavaCompile(){
		fc = new JFileChooser();
		fin=null;
		if(fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			 fin = fc.getSelectedFile();
			 name = fin.getName();
			 path = fin.getAbsolutePath();
		}



		cmd = new String[7];
		cmd[0] = "command.com";	
		cmd[1] = "/C";
		cmd[2] = "set PATH=C:\\Program Files\\Java\\jdk1.6.0_04\bin";
		cmd[3] = "cp "+path+"\\name"+ " C:\\java";
		cmd[4] = "cd C:\\java";
		cmd[5] = "javac *.java";
		cmd[6] = "jar cmf mainClass.txt"+" name"+".jar *.class";

		try{
		Runtime.getRuntime().exec(cmd);
		}
		catch(Exception e){
			System.out.println("Error		}
		}
}

Link to comment
https://www.neowin.net/forum/topic/620450-java-runtimegetruntimeexec-help/
Share on other sites

14 answers to this question

Recommended Posts

  • 0
  night_stalker_z said:
What sort of problems are you getting. It might be a limitation of the command prompt.

When i run it, my try catch block goes off and prints "Error".

None of the files get moved to the hoped for directory and i never see command.com open, though it may be too fast.

  • 0
  night_stalker_z said:
You might need to change this line

cmd[3] = "cp "+path+"\\name"+ " C:\\java";

make sure its got quotes around it if the path contains spaces.

And in your catch block, print e.getMessage(); as thats more descriptive.

I'll try this and report back soon. Thanks :D

  • 0

Wait, gotta ask a stupid question, I'm assuming you're trying to run a copy command to copy the file to a certain location and then compile it? (that's how I read it)

Do you not want:

cmd[3] = "copy "+path+"\\name"+ " C:\\java";

as "cp" isn't a valid Command Prompt command, but a Unix command for copy?

Sorry if I'm missing the obvious!

  • 0
  McSmiggins said:
Wait, gotta ask a stupid question, I'm assuming you're trying to run a copy command to copy the file to a certain location and then compile it? (that's how I read it)

Do you not want:

cmd[3] = "copy "+path+"\\name"+ " C:\\java";

as "cp" isn't a valid Command Prompt command, but a Unix command for copy?

Sorry if I'm missing the obvious!

Way to make me feel moronic XD Good catch! This is my code now, which runs fine but does nothing :( . doesnt even spit errors. Help?

import javax.swing.JFileChooser;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;

public class JavaCompile {
	private String[] cmd;
	private String name;
	private JFileChooser fc;
	private File fin;
	private String path;



	public static void main(String[] args){
		JavaCompile jc = new JavaCompile();
	}



	public JavaCompile(){
		fc = new JFileChooser();
		fin=null;
		if(fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			 fin = fc.getSelectedFile();
			 name = fin.getName();
			 path = fin.getAbsolutePath();
		}



		cmd = new String[7];
		cmd[0] = "cmd";	
		cmd[1] = "/C";
		cmd[2] = "set PATH=C:\\Program Files\\Java\\jdk1.6.0_04\bin";
		cmd[3] = "copy " + "\"" +path + "\\" +name+ "\"" + " C:\\java";
		cmd[4] = "chdir C:\\java";
		cmd[5] = "javac *.java";
		cmd[6] = "jar cmf mainClass.txt"+" name"+".jar *.class";

		try{
		Runtime.getRuntime().exec(cmd);
		System.out.println("runningands");		
		}
		catch(Exception e){
			System.out.println(e.getMessage());
			System.out.println("runningands2");
			}
		System.out.println("runningands3");
		}
}

Maybe i have to use Canonical file paths? I'm not sure of the difference.

Edited by Mortiferous
  • 0
  _kane81 said:
you should really use a platform independent soluion

http://www.java2s.com/Code/Java/File-Input...ngJavaIOAPI.htm

or here

http://forum.java.sun.com/thread.jspa?thre...ssageID=3841126

they have an example of using cmd too

Indeed, there's native Java solutions for doing this, so why would you want to execute a shell command? Even easier than what was in that first link is the Commons VFS API: http://commons.apache.org/vfs/

FileSystemManager fsManager = VFS.getManager();
FileObject origFile = fsManager.resolveFile("originalFile");
FileObject newFile = fsManager.resolveFile("newFile");
/*Possibly any checks here on both files, or just stick in a try/catch as the next function will throw an exception if it can't do anything*/
origFile.moveTo(newFile);
/*Or just copy:*/
newFile.copyFrom(origFile,new AllFileSelector());

Note this will work on files or directories.

Edited by kjordan2001
  • 0
  kjordan2001 said:
Indeed, there's native Java solutions for doing this, so why would you want to execute a shell command? Even easier than what was in that first link is the Commons VFS API: http://commons.apache.org/vfs/

FileSystemManager fsManager = VFS.getManager();
FileObject origFile = fsManager.resolveFile("originalFile");
FileObject newFile = fsManager.resolveFile("newFile");
/*Possibly any checks here on both files, or just stick in a try/catch as the next function will throw an exception if it can't do anything*/
origFile.moveTo(newFile);
/*Or just copy:*/
newFile.copyFrom(origFile,new AllFileSelector());

Note this will work on files or directories.

A Little over my head, but if i did get that to work, ide still be stuck on how to run javac to compile it to a jar.

  • 0

Bump. Anyone know of a way to do this by calling the command prompt? I cont care to make this platform independent, because its for personal use mostly. I've decided that instead of trying to copy the file, i'll just use a printWriter to do the same thing, that part of my code works. My Current code looks like:

import javax.swing.JFileChooser;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;

public class JavaCompile {
	//fields
	private String[] cmd;
	private String name;
	private JFileChooser fc;
	private File fin;
	private File fout;
	private String path;
	private String pathtest;
	private Scanner in;
	private PrintWriter print;

	//Main Method
	public static void main(String[] args){
		JavaCompile jc = new JavaCompile();
	}


	//Constructor
	public JavaCompile(){
		//initialize fields
		fc = new JFileChooser();
		fin=null;
		fout = null;
		print = null;
		in = null;

		//Select the File to copy
		if(fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			 fin = fc.getSelectedFile();
			 name = fin.getName();
			 try{
			 pathtest = fin.getCanonicalPath();
			 }catch(Exception e){
				 System.out.println(e.getMessage());
			 }
		}
		//select where to copy the file, then copy it.
		if(fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			  fout = fc.getSelectedFile();
		  }

		  try {
			in = new Scanner(fin);
			print = new PrintWriter(fout);
			while (in.hasNextLine()) {
				String s = in.nextLine();

						print.println(s);

			}
			in.close();
			print.close();

		 } catch (Exception e) {
			 System.out.println("Errorrated by print writer:");
			 System.out.println(e.getMessage());
		 }

		//Creates list of commands to call 
		cmd = new String[6];
		cmd[0] = "cmd.exe";	
		cmd[1] = "/c";
		cmd[2] = "chdir";
		cmd[3] = "C:\\Program Files\\Java\\jdk1.6.0_04\\bin";
		cmd[4] = "javac";
		cmd[5] = "C:\\java\\Calculator.java";


		try{
		Runtime.getRuntime().exec(cmd);
		System.out.println("runningands");		
		}
		catch(Exception e){
			System.out.println(e.getMessage());
			System.out.println("runningands2");
			}
		System.out.println("runningands3");
		}
}

  • 0
  Mortiferous said:
A Little over my head, but if i did get that to work, ide still be stuck on how to run javac to compile it to a jar.

Ah, you also might look into ant or maven for this kind of thing (automated build systems). I've seen hibernate put up a JWindow while compiling, so it may also be likely to be able to put up a JFileChooser, but more than likely it would be easier to just copy the build.xml into each project you want to build and you can build it generically enough with wildcards that it'll compile any java source.

Another option is an IDE like eclipse where it'll automatically compile once you save it and it has an export to jar option.

  • 0

Hi Mortiferous,

Any updates on Runexec....

I have a similar issue wherein I am trying to compile a java file by invoking command prompt...But it does not work

I tried out two different options:

Option 1

Runtime rt = Runtime.getRuntime();

Process proc = rt.exec("cmd.exeet classpath=%classpath%;Y:\\applications\\maximo\\businessobjects\\classes;Y:\\applications\\maximo\\maximouiweb\\webmodule\\WEB-INF\\classes");

proc = rt.exec("cmd.exeet path=%path%;C:\\bea\\jdk142_05\\bin;.");

proc = rt.exec("cmd.exec Y:\\applications\\maximo\\businessobjects\\classes\\psdi\\MXIDE\\WOExt.java");

InputStream stderr = proc.getErrorStream();

InputStreamReader isr = new InputStreamReader(stderr);

BufferedReader br = new BufferedReader(isr);

String line = null;

while ((line = br.readLine())!= null)

System.out.println(line);

int exitval = proc.waitFor();

System.out.println ("Process Exit Value:" + exitval);

Option 2:

String[] cmd;

cmd = new String[8];

cmd[0] = "cmd.exe";

cmd[1] = "/c";

cmd[2] = "set";

cmd[3] = "PATH=%PATH%;C:\\bea\\jdk142_05\\bin";

cmd[4] = "set";

cmd[5] = "classpath=%classpath%;Y:\\applications\\maximo\\businessobjects\\classes;Y:\\applications\\maximo\\maximouiweb\\webmodule\\WEB-INF\\classes";

cmd[6] = "javac";

cmd[7]= "Y:\\applications\\maximo\\businessobjects\\classes\\psdi\\MXIDE\\WOExt.java";

Runtime rt = Runtime.getRuntime();

Process proc = rt.exec(cmd);

InputStream stderr = proc.getErrorStream();

InputStreamReader isr = new InputStreamReader(stderr);

BufferedReader br = new BufferedReader(isr);

String line = null;

while ((line = br.readLine())!= null)

System.out.println(line);

int exitval = proc.waitFor();

System.out.println ("Process Exit Value:" + exitval);

When I run option-1 the classpath is not getting set properly and on running javac, it is throwing unreferenced errors on imported class files. When I run option-2, it does not throw any error...But nothing happens. The program returns an exitvalue of 0, but still the class file does not get created....

Any suggestions will be greatly appreciated!!

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I value a game as a whole including graphics. But going backwards in terms of graphics with a game I'm not already invested in (as in something I played and loved in the past and still do) is off-putting. Its a very poor demo trailer if they didn't crank the settings to max that would be ridiculous. Different strokes for different folks i guess, i'm not into slop the trailer and likely game could have been far better, it doesn't it instead looks like it was made on a shoe string budget or with lack of experience. But that could also be down to trying to get it running on low budget/outdated hardware and sacrificing the top end.
    • > Our goal is to ensure that the App Store remains an outstanding opportunity for developers and a safe, trusted experience for our users. There are so many scam apps on the platform that it is hard to believe they are truly interested in having a safe, trusted experience for their users.
    • Google announces upgraded Gemini 2.5 Pro model with enhanced capabilities by Pradeep Viswanathan Google today announced an updated Gemini 2.5 model with several improvements that can be observed in popular AI benchmarks. Google particularly highlighted that the new Gemini 2.5 Preview 06-05 "Thinking" model performs better in coding, math, science, and reasoning. Last month, during Google I/O, Google released an updated version of the Gemini 2.5 Pro model with significant improvements. Today's update builds on the release of the previous month with further enhancements. In addition to benchmark improvements, based on user feedback, this updated Gemini 2.5 Pro model also comes with improved style and structure, which will result in creative and better-formatted responses for end users. You can find the benchmark comparison with other leading AI models below. As you can notice in the above table, this updated Gemini 2.5 Pro preview model is now SOTA (State-of-the-Art) in coding benchmarks like Aider Polyglot. It also scored SOTA performance on GPQA and Humanity’s Last Exam (HLE) benchmarks, which test math, science, knowledge, and reasoning capabilities. In real-world testing, this latest 2.5 Pro model scored 24 points better on LMArena, maintaining its lead, and a 35-point jump on WebDevArena at 1443. Developers can access this latest Gemini 2.5 Pro preview model through the Gemini API via Google AI Studio and Vertex AI. General consumers will be able to access this model via the Gemini app. Google also confirmed that the Gemini 2.5 Pro model will be generally available in a couple of weeks, allowing developers to start using it in production-ready enterprise-scale applications.
    • The Bromance is definitely over! 🤣🤣🤣
    • I have the chance to live where electricity comes only from dams.
  • Recent Achievements

    • Week One Done
      jbatch earned a badge
      Week One Done
    • First Post
      Yianis earned a badge
      First Post
    • Rookie
      GTRoberts went up a rank
      Rookie
    • First Post
      James courage Tabla earned a badge
      First Post
    • Reacting Well
      James courage Tabla earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      418
    2. 2
      +FloatingFatMan
      181
    3. 3
      snowy owl
      178
    4. 4
      ATLien_0
      174
    5. 5
      Xenon
      135
  • Tell a friend

    Love Neowin? Tell a friend!