• 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

    • The word "standard" has a very broad set of definitions that covers many uses beyond technical standards. Also, "de facto standard" is a common phrase with its own meaning, which I used correctly.
    • Just want to throw in my two current favorite streaming shows both of which have brilliant theme songs.  Added bonus. Another fun new show is called Duster starring Josh Hollaway. It's opening theme is brilliant.  
    • Depends on where you are from. I know in the US they love their Messages because ISPs there were blocking mobile data for certain apps, especially messengers and voip apps because they wanted to sell bundles of call minutes and sms messages (the reason why Skype was not so popular in US as Microsoft expected - at the very beginning it just couldn't run on mobile data at all in US). Here in EU I don't know anyone using Messages because we moved to better messenger apps long ago. I've used a Java version of ICQ and Google Talk on my dumb phone before the iPhone was a thing.
    • Do we really need to bring more attention to yt-dlp? I'm sure that project will be pulled if it becomes super common knowledge.
    • Windows Photos gets AI-powered light controls and improved search by Taras Buria Microsoft is rolling out a new update for the Windows Photos app in the Insider program. Today's release introduces two new AI-powered features: light controls (Relight) and search with natural language (initially announced in early May 2025). With Relight, users can set up to three light sources on a single image and customize their light color, focus point, brightness, and intensity. The app has built-in presets for quick light adjustments and styles, which you can apply with a single click. Microsoft says that besides styling your photos, Relight can correct poor lighting on images to make them look better. As of right now, Relight is only available to Windows Insiders with Snapdragon-powered Copilot+ PCs. However, Microsoft promises to release the feature to users with AMD and Intel-based Copilot+ PCs in the coming months. Next is improved search, which is now semantically based, allowing you to find photos using natural language. For example, you can search for "sunset at the beach" or "family outdoor fun." Windows Photos will use AI to understand your request and find photos that best fit it. Note that improved search only works with locally stored and indexed pictures in the Pictures library. More information about indexing and supported languages is available in the official documentation. Finally, two Windows Photos features are now available to Entra ID users: Restyle Image and Image Creator. Previously, these features were only available to customers with standard Microsoft Accounts. For reference, Restyle Image lets you use AI to reimagine your photo in a different style, while Image Creator enables you to generate pictures using text prompts. The new features for the Windows Photos app are now rolling out in all Insider channels in version 2025.11060.5006.0 and higher. You can read more about them in the official announcement post.
  • Recent Achievements

    • Mentor
      Karlston went up a rank
      Mentor
    • One Month Later
      EdwardFranciscoVilla earned a badge
      One Month Later
    • One Month Later
      MoyaM earned a badge
      One Month Later
    • One Month Later
      qology earned a badge
      One Month Later
    • One Year In
      Frinco90 earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      481
    2. 2
      snowy owl
      257
    3. 3
      +FloatingFatMan
      253
    4. 4
      ATLien_0
      215
    5. 5
      Xenon
      151
  • Tell a friend

    Love Neowin? Tell a friend!