Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Problem Multiple Commands and filepath or classpath.

  1. #1
    Member Andrew R's Avatar
    Join Date
    Jul 2013
    Location
    San Pedro Sula, Honduras
    Posts
    58
    My Mood
    Inspired
    Thanks
    11
    Thanked 1 Time in 1 Post

    Question Problem Multiple Commands and filepath or classpath.

    Hello there forum!

    I've been dealing with something piece of cake. Right.
    Piece of difficult cake.

    So here is my personal project I've been working on, and I've already been receiving help from some of you (thanks!!! ) helping me get out mindfarts.

    One of the objectives of this app is to be able to create a .java then compile it, and execute the file in runtime.

    So far, my program is completely functional but I am facing a major challange.
    I am only able to make it partially work when I give the program a predefined location. I decided to be able to make use a static variable Location, and some other variables sent as parameters to compile and execute.

    What I've been doing all along was Runtime.getRuntime().exec(command); to access the cmd and compile or execute the desired file, and I haven't been able to get to where I want. I started reading about the ProcessBuilder class, and I don't get it.

    Been close to 4 to 5 hours trying to figure this one out. It has become a royal pain in the butt.

    Any suggestion or assistance would be greatly appreciated by this fellow here.

    import java.io.*;
    import java.util.*;
     
    public class Mercury {
     
        static private Vector <String> SAVEDDIR = new Vector <String>(0, 1);
    	static private String Path;
    	static private String Code;
    	static private String Name;
    	static private String Location;
     
    	private static String setLocation(){
    	    String SubLocation = ""; /** ! ei. "C:\\Users\\Andrew\\Desktop//" */
    		return "C:\\" + SubLocation;
    	}
     
    	private static String nameCreator(){	
    		Random R = new Random();
    		int i; String name = ""; char lower;
    		for(int k = 0; k < 7; k++){ i = R.nextInt(26)+65; name = name + (char)i; name = name.toLowerCase(); }
    		return name;
    	}
     
    	private static String codeGenerator(){
    	    String Body = ""; /** ! */
    		return ("import java.io.*;\nimport java.util.*;\n\npublic class " + Name + " {    \n" + Body + "\n}");
    	}
     
    	private static void setCreationParameters(){
    	    Name = nameCreator();
    		Location = setLocation();
    		Path = Location + Name + ".java";
    		Code = codeGenerator();
        }
     
    	private static void createFile(String ParamPath, String ParamCode){
    		File file = new File(ParamPath);
    		boolean blnCreated = false;
    		try { blnCreated = file.createNewFile(); }
            catch(IOException ioe) { System.out.println("Error while creating a new empty file :" + ioe); }
            System.out.println("Was file " + file.getPath() + " created ? : " + blnCreated);
            boolean blnWritten = false;
    	    try { blnWritten = file.canWrite(); 
    		      FileWriter writer = new FileWriter(file);
                  writer.write(ParamCode);
    		      writer.flush();
                  writer.close(); }
    		catch(IOException ioe2) { System.out.println("Error while writing in file :" + ioe2); }
            System.out.println("Was file " + file.getPath() + " written ? : " + blnWritten);
    		SAVEDDIR.addElement(ParamPath);
    	}
     
    	private static void createFile() { createFile(Path,Code); }
     
        private static void printLines(String name, InputStream ins) throws Exception {
            String line = null;
            BufferedReader in = new BufferedReader( new InputStreamReader(ins) );
            while ((line = in.readLine()) != null) { 
                System.out.println(name + " " + line);
            }
        }
     
        private static void runProcess(String command) throws Exception {
            Process pro = Runtime.getRuntime().exec(command);
            printLines(command + " stdout:", pro.getInputStream());
            printLines(command + " stderr:", pro.getErrorStream());
            pro.waitFor();
            System.out.println(command + " exitValue() " + pro.exitValue());
        }
     
    	private static void compileFile(){
            try{ runProcess(new String[] { "cd " + Path + "; javac " + Name + ".java" } ); } catch (Exception e) {e.printStackTrace(); }
    	}
     
    	private static void executeFile(){ // Needs 
    		try{ runProcess(new String[] { "cd " + Path + "; java " + Name } ); } catch (Exception e) { e.printStackTrace(); }
    	}
     
    	public static void main(String[] args) {
     
    		setCreationParameters();
    		createFile();
    		compileFile();
            executeFile();
     
        }
     
    }

    So yeah. Long story short, how can I get this part to work. Should I change strategy?:

        .
        .
        .
    	private static void compileFile(){
            try{ runProcess(new String[] { "cd " + Path + "; javac " + Name + ".java" } ); } catch (Exception e) {e.printStackTrace(); }
    	}
     
    	private static void executeFile(){ // Needs 
    		try{ runProcess(new String[] { "cd " + Path + "; java " + Name } ); } catch (Exception e) { e.printStackTrace(); }
    	}
        .
        .
        .

    If I only place one cmd, removing the "new String[] { ... }" decor it works only when the file is at the default context I selected in the command prompt. In the mean time, I am unable to compile program its says..

    C:\Users\Andrew\Desktop>javac Mercury.java
    Mercury.java:72: error: method runProcess in class Mercury cannot be applied to
    given types;
    try{ runProcess(new String[] { "cd " + Path + "; javac " + Name + ".java
    " } ); } catch (Exception e) {e.printStackTrace(); }
    ^
    required: String
    found: String[]
    reason: actual argument String[] cannot be converted to String by method invoc
    ation conversion
    Mercury.java:76: error: method runProcess in class Mercury cannot be applied to
    given types;
    try{ runProcess(new String[] { "cd " + Path + "; java " + Name }
    ); } catch (Exception e) { e.printStackTrace(); }
    ^
    required: String
    found: String[]
    reason: actual argument String[] cannot be converted to String by method invoc
    ation conversion
    2 errors


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Problem Multiple Commands and filepath or classpath.

    I am unable to compile program

    required: String
    found: String[]
    This part of the error message tells you what it wrong. The runProcess() method takes a String.
    The code is trying to pass it a String[] array.

    The exec() method can take an array, so try changing the args to runProcess() to take an array.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    Andrew R (August 10th, 2013)

  4. #3
    Member Andrew R's Avatar
    Join Date
    Jul 2013
    Location
    San Pedro Sula, Honduras
    Posts
    58
    My Mood
    Inspired
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: Problem Multiple Commands and filepath or classpath.

    I see! Okay I'll try that.

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Problem Multiple Commands and filepath or classpath.

    I don't know if the exec() method will execute more that one command. If you want to have multiple DOS commands executed with one call to the exec() method, look at using a batch file that contains all the DOS commands.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #5
    Member Andrew R's Avatar
    Join Date
    Jul 2013
    Location
    San Pedro Sula, Honduras
    Posts
    58
    My Mood
    Inspired
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: Problem Multiple Commands and filepath or classpath.

    Well, I just need to post this for my own reference, general rule is, whatever I need, its probably already invented so. getRuntime()... might have a method or two for String[]. I was stuck in that a lot of time.

    Java.lang.Runtime.exec(String command, String[] envp, File dir) Method Example
    public Process exec(String command, String[] envp, File dir)

    Java.lang.Runtime.exec(String[] cmdarray, String[] envp) Method Example
    public Process exec(String[] cmdarray, String[] envp)

    Java.lang.Runtime.exec(String[] cmdarray) Method Example
    public Process exec(String[] cmdarray) Currently this one is the one I'm trying. Well its showing an error I've never seen before. I'll figure it out.

    --- Update ---

    So I've tried

        .
        .
        .
    	private static void compileFile(){
            try{ runProcess(new String[] { "cd " + Location + "; javac " + Name + ".java" } ); } catch (Exception e) {e.printStackTrace(); }
    	}
     
    	private static void executeFile(){ // Needs 
    		try{ runProcess(new String[] { "cd " + Location + "; java " + Name } ); } catch (Exception e) { e.printStackTrace(); }
    	}
        .
        .
        .

    There is no further conflict with the types, also corrected instructions changing "Path" to "Location".

    In theory, the info sent would be "cd C:\" and should work, but it isn't. If I add "cmd" to the beggining of the command array it would display two lines of a description of the cmd prompt, but will not recognize "cd C:\" as a command, freezes or will not complete the process.

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Problem Multiple Commands and filepath or classpath.

    For debugging its useful to print out the contents of the array that is passed to the exec() method.
    Something like: System.out.println("an ID "+ java.util.Arrays.toString(theArrayName));


    Are there any error messages returned on the Process's error stream?
    If you don't understand my answer, don't ignore it, ask a question.

  8. #7
    Member Andrew R's Avatar
    Join Date
    Jul 2013
    Location
    San Pedro Sula, Honduras
    Posts
    58
    My Mood
    Inspired
    Thanks
    11
    Thanked 1 Time in 1 Post

    Default Re: Problem Multiple Commands and filepath or classpath.

    There are no error messages returned on the Process's error stream.

    --- Update ---

    by the way I have tried changing the code again taking advantage of the shell operator "&&" and remove the String[].

    	private static void compileFile(){
            try{ runProcess("cd " + Location + " && " + "javac " + Name + ".java"); } catch (Exception e) {e.printStackTrace(); }
    	}
     
    	private static void executeFile(){
    		try{ runProcess("cd " + Location + " && " + "java " + Name); } catch (Exception e) { e.printStackTrace(); }
    	}

    It did compile as well. However I tried to run this code, and with this change I got:

    C:\Users\Andrew\Desktop\Wish List>java Mercury
    Was file C:\aajppwd.java created ? : true
    Was file C:\aajppwd.java written ? : true
    java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system
    cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at Mercury.runProcess(Mercury.java:64)
    at Mercury.compileFile(Mercury.java:83)
    at Mercury.main(Mercury.java:94)
    Caused by: java.io.IOException: CreateProcess error=2, The system cannot find th
    e file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 7 more
    java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system
    cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at Mercury.runProcess(Mercury.java:64)
    at Mercury.executeFile(Mercury.java:87)
    at Mercury.main(Mercury.java:95)
    Caused by: java.io.IOException: CreateProcess error=2, The system cannot find th
    e file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 7 more

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,147
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Problem Multiple Commands and filepath or classpath.

    Cannot run program "cd"
    That says the program "cd" can't be found. Some commands are NOT programs but are part of the DOS environment defined by another program. Try some other commands. For example the "cmd" command.

    Create a batch file and see if the program can execute it.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Problem with LogIn - Multiple users
    By justyStepi in forum AWT / Java Swing
    Replies: 5
    Last Post: April 28th, 2012, 12:18 PM
  2. Replies: 1
    Last Post: March 31st, 2012, 06:52 PM
  3. Installing JMF, setting up Classpath in Netbeans Problem
    By chronoz13 in forum Java Theory & Questions
    Replies: 0
    Last Post: May 19th, 2011, 09:11 AM
  4. [SOLVED] CLASSPATH environment variable
    By SPACE MONKEY in forum Java Theory & Questions
    Replies: 6
    Last Post: February 15th, 2011, 04:10 PM
  5. Problems in setting classpath
    By missyati in forum Java Theory & Questions
    Replies: 3
    Last Post: June 30th, 2009, 12:43 AM

Tags for this Thread