• 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

    • 2TB Samsung 990 EVO Plus SSD drops to a great price again by Fiza Ali The 2TB Samsung 990 EVO Plus SSD is currently available on Amazon, Samsung, and Newegg at a great price, only $0.44 higher than its historic low. So, if you have been wanting to upgrade your storage solution, you may want to check it out (purchase links down below). The SSD features NAND memory, delivering sequential read speeds of up to 7,250MB/s and write speeds of up to 6,300MB/s. For random read (QD32), the 2TB version reaches up to 1,000K IOPS, and for random write (QD32), it achieves up to 1,350K IOPS. Furthermore, it carries a Total Bytes Written (TBW) rating of 1,200. The 990 EVO Plus is equipped with Intelligent TurboWrite 2.0 for enhanced performance with large files. Moreover, the drive features a nickel-coated controller that helps manage heat, reduce power usage, and prevent overheating. The SSD supports both PCIe 4.0 x4 and PCIe 5.0 x2, promising faster data transfer speeds and better performance. Additionally, with Samsung's Magician Software, the SSD keeps its firmware up to date, adds extra security, and allows for continuous drive health monitoring. Finally, the Samsung 990 EVO Plus SSD comes with a five year limited warranty, offering long-term reliability and peace of mind. 2TB Samsung 990 EVO Plus SSD: $129.99 (Amazon US) - $129.99 (Samsung US) - $129.99 (Newegg) This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. You can also check out other SSD deals here. For hard disk drives, you can head over to our HDD deals section to see if anything from there matches your requirements. Make sure you also browse through Amazon US, Amazon UK, and Newegg US to find some other great tech deals. As an Amazon Associate, we earn from qualifying purchases.
    • As visually pleasing as elementaryos (and pantheon) is, I found it to be a little too far behind on some things. I wish they would package their desktop environment for use on other distros. Unfortunately their dev team is pretty small and it just naturally takes a long time for them to get things polished.
    • I was thinking, and was going to post, almost exactly what @Brandon Hjust posted!   WARNING: possible spoilers I also love these videos she makes:   
    • The Witcher 4 tech demo shows off the RPG in action on a base PS5 at 60FPS by Pulasthi Ariyasinghe Epic Games' The State of Unreal 2025 keynote happened today, giving a look at its latest improvements to the Unreal Engine, and other developments and partnerships that the Fortnite maker is involved in. The show kicked things off with a bang, giving fans a live on-stage presentation of The Witcher 4 alongside developer CD Projekt RED. Seen below, the tech demo of the hugely anticipated RPG features the new trilogy's protagonist, Ciri, as she explores Kovir, the new mainland that CD Projekt is letting players explore. Following a monster trail, Ciri and her horse Kelpie go through mountains and forests before reaching the town of Valdrest. Surprisingly, the demo is said to be running on a base PlayStation 5, and it even manages to stay at 60 frames per second despite the stunning visuals. The studio said that the technologies it is using will benefit all platforms that it is targeting for the RPG. The Witcher 4 is coming to PC, Xbox Series X|S, and PlayStation 5 consoles, though a release date has not been revealed yet. "We started our partnership with Epic Games to push open-world game technology forward. To show this early look at the work we’ve been doing using Unreal Engine running at 60 FPS on PlayStation 5, is a significant milestone — and a testament of the great cooperation between our teams," said joint CEO of CD Projekt RED Michał Nowakowski. "But we're far from finished. I look forward to seeing more advancements and inspiring technology from this partnership as development of The Witcher 4 on Unreal Engine 5 continues." The demo showcases tech like Unreal Animation Framework, Nanite Foliage rendering, MetaHuman technology with Mass AI crowd scaling, and more from Epic Games' latest engine developments. Unreal Engine 5.6 is said to include many of these improvements, letting any developer use the tools on their games for better visuals and optimizations.
    • The same guy who promised AGI in a year, and later he said: yes, but no really.
  • Recent Achievements

    • Week One Done
      Adam Todd earned a badge
      Week One Done
    • Contributor
      Ed B went up a rank
      Contributor
    • One Month Later
      moporcho earned a badge
      One Month Later
    • One Month Later
      Parotel earned a badge
      One Month Later
    • Reacting Well
      Cryptecks earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      202
    2. 2
      snowy owl
      145
    3. 3
      ATLien_0
      133
    4. 4
      Xenon
      120
    5. 5
      +FloatingFatMan
      108
  • Tell a friend

    Love Neowin? Tell a friend!