• 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

    • VR is dead on the PS at this rate, sales just aren't there. Way more VR push on the PC, even Sony knows this and that's why they added PC support to the PSVR.
    • Borderlands series, Rematch, Broken Arrow, and more get Nvidia GeForce NOW support by Pulasthi Ariyasinghe Another Nvidia GeForce NOW games update has arrived, meaning subscribers now have even more games to jump into via the cloud if they own a copy. The latest wave touts 13 more games, and that includes the Borderlands franchise from Gearbox, Remedy's brand-new cooperative shooter FBC: Firebreak, and more. With the fourth entry now on the way, for those who have yet to jump into Gearbox's wacky looter shooter universe, Borderlands, Borderlands 2, Borderlands 3, and even Borderlands: The Pre-Sequel are now a part of GeForce NOW. The Sifu developer's rule-less soccer experience, Rematch, has also been released to standard edition owners today. With the latest update, for owners of the game or PC Game Pass subscribers, it is also accessible via the cloud on GeForce NOW. Here are the games announced for the program this week: REMATCH (New release on Steam, Xbox, available on PC Game Pass, June 16) Broken Arrow (New release on Steam, June 19) Crime Simulator (New release on Steam, June 17) Date Everything! (New release on Steam, June 17) FBC: Firebreak (New release on Steam, Xbox, available on PC Game Pass, June 17) Lost in Random: The Eternal Die (New release on Steam, Xbox, available on PC Game Pass, June 17) Architect Life: A House Design Simulator (New release on Steam, June 19) Borderlands Game of the Year Enhanced (Steam) Borderlands 2 (Steam, Epic Games Store) Borderlands 3 (Steam, Epic Games Store) Borderlands: The Pre-Sequel (Steam, Epic Games Store) METAL EDEN Demo (Steam) Torque Drift 2 (Epic Games Store) As always though, keep in mind that unlike subscription services like Game Pass, a copy of a game must be owned by the GeForce NOW member (or at least have a license via PC Game Pass) to start playing via Nvidia's cloud servers.
    • WHAT? First of all, Azure, literally, runs on THE LINUX KERNEL. I know, right? Windows is easier to develop drivers? This must be the joke of the century! Developing drivers on Linux, you can interact with low level implementation straight to the core. You can build and test them with standard tools like GCC and Make, no need for a full blown IDE or SDKs, only a kernel header and a Makefile. You can load/unload drivers dynamically, without rebooting, which makes debugging MUCH easier. You don't need to sign drivers, unlike Windows, even for local testing. And a ton of other conveniences. "There is no way a Linux distribution can compete against Windows". Literally, SteamOS competes against Windows on handhelds, playing games WRITTEN for Windows, BETTER than Windows. "DirectX is the most powerful API"? Really? Vulkan provides more low level control, less overhead, scales better with more threads, it's cross platform and extensible. How, exactly, is "DirectX the most powerful API"?
    • It's easier for the console market to pull in more revenue when they're prices are higher compared to the PC where games often come out cheaper than their console versions or go on sale quicker. Having said that, I'm not going to be paying $70 or $80 for a game, regardless of the platform it's on. Revenue aside, because raising prices on consoles skew things when the prices on the PC often stay around the same levels, it's been shown that the PC market is growing while the console market is overall flat. PC will pass consoles soon dropping them into 3rd place. And the PS5 being on track to pass the PS4 doesn't say much, if the console market was actually still growing Sony would've passed the PS2 as it's best selling console with the PS3, and the PS4 would've outsold both and so on. That's not happening. It took Nintendo to release a totally different hybrid system with the Switch to inject some new life into the "console" market. Even then it's pushed as a handheld first and the majority who buy it do so because it's portable and at a good price.
    • As with the rest of the misleading statement you made about SteamOS "limitations", you are wrong again. No, the XBOX does NOT run "slimmed down and modified Windows". It runs a HEAVILY modified version of the Hyper-V hypervisor, called "Nanovisor" and 2 VM partitions. One for games, one for the apps. It is NOT Windows, it can NOT run Windows games and its DirectX components are NOT the same as for Windows, they are customized for XBOX.
  • Recent Achievements

    • First Post
      MikeK13 earned a badge
      First Post
    • One Month Later
      OHI Accounting earned a badge
      One Month Later
    • Week One Done
      OHI Accounting earned a badge
      Week One Done
    • First Post
      Thornskade earned a badge
      First Post
    • Week One Done
      Higante88 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      717
    2. 2
      ATLien_0
      273
    3. 3
      Michael Scrip
      203
    4. 4
      +FloatingFatMan
      182
    5. 5
      Steven P.
      128
  • Tell a friend

    Love Neowin? Tell a friend!