• 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

    • Nvidia App gets light theme, bug fixes, and support for more games by Taras Buria Nvidia has released a new update for the Nvidia App on Windows. Version 11.0.4 is now available with a few changes, such as automatic theme switching with light mode support, Windows Narrator support, fixed bugs, and optimal settings for 12 new games. With today's update, Nvidia App now supports light mode. You can switch between modes in settings or let the app follow the system settings (Windows still does not support automatic theme switching). To change the mode, go to Settings > Features > Theme. In addition, Nvidia App now supports Windows Narrator. The system's native screen reader can now properly read aloud on-screen content to improve accessibility for those relying on assistive technologies. Next, the list of games that Nvidia App can tune for optimal performance has been extended with 12 new titles: Assassin's Creed: Shadows Clair Obscur: Expedition 33 Deadlock ELDEN RING NIGHTREIGN Grand Theft Auto V Enhanced Half-Life 2 with RTX Indiana Jones And The Great Circle inZOI Monster Hunter Wilds Split Fiction The Last of Us Part II Remastered The Elder Scrolls IV: Oblivion Remastered Finally, Nvidia App 11.0.4 fixes the following bugs: Fixed an issue where DLSS-FG defaults to 2x irrespective of in-game setting when DLSS override model is set to "Latest” and Frame generation is set to “Use the 3D application setting". Fixed an issue where the driver download could not be completed. Fixed an issue where the recording bitrate setting was not saved. Fixed an issue where HDR video colors were not encoded properly for HEVC and AV1 playback. Fixed a bug where the in-game overlay was not accessible on the GeForce RTX 5070. Fixed an issue where a PC reboot would reset microphone boost to an incorrect value. Fixed an issue where Highlights summary window could not be disabled. Various stability fixes. You can download the Nvidia App from the official website. Full release notes are available here.
    • Ai is terrible at showing us existing knowledge. Hallucinating s**t is not exactly "discovering".
    • You know, this is mostly Edge related? It also affects just EU people.
  • Recent Achievements

    • Conversation Starter
      lilyandrew11 earned a badge
      Conversation Starter
    • 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
      188
    2. 2
      snowy owl
      135
    3. 3
      ATLien_0
      131
    4. 4
      Xenon
      120
    5. 5
      +FloatingFatMan
      100
  • Tell a friend

    Love Neowin? Tell a friend!