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 12 of 12

Thread: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

  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

    Default Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    Hello foums!

    How are you? I've been wrestling for like about 2 weeks trying to nail this problem.

    the Objective:

    I am working on a main class that creates another .java, at the desired location.
    The idea is to have my original program, which created the .java file to compile and have the cmd execute its .class version which is at the desired location.

    Before you suggest there are different ways to have another class executed, the problem I am facing is a necessary one.
    I am trying to create a stand alone main class, that doesn't rely in any other code than the one it has on its own. With that in mind, I am trying to add the abbility for the stand alone class to create another main class, and for it to be executed by the cmd.

    Its pretty complicated so far. But how I see it, in the big picture, what I am trying to do is probably something out-of-the-box.

    Approches I've tried:

    Originally I started with Runtime getRuntime() exec(String command), which basically sends a String which is interpreted as a cmd instruction. So far so good. However, I am only able to compile and execute files that are on the same directory or path my original java program is under. That is as far as I can go.

    Common sense is to type in the "cd locationofthefile". So I had two Runtime getRuntime() exec(String command) run one receiving the "cd ..." and the rest receiving the command I was prettending to use. Unfortunately, it did not work.

    I then attempted to use Runtime getRuntime() exec(String [] command) which is able to receive as much commands I'd like, and unfortunately sort of instanciates another cmd with its own environment per command. So using "cd ..." would not work.

    Got back to the Runtime getRuntime() exec(String command) taking advantage of some operator available in the cmd prompt like "&&" to send a single String with two instructions. However getRuntime() exec() sort of "tokenizes" each command, going back to the problem before.

    Then I tried just sending a single "cd ..." see if would work and it doesnt. Apparently "cd" is not a program thus it doesn't recognize the cmd instruction. Also attempted to initiate the cmd first, and afterwards send, the "cd... " instruction, and other commands. Seems to me Runtime getRuntime() exec(String command), and Runtime getRuntime() exec(String [] command) are just dead ends.

    What I haven't tried:

    So others have suggested using a ProcessBuilder, I really haven't tested it much. I am new at managing exceptions, input and output Streams, and understanding subprocesses and that stuff. I am not skilled in that yet. However the logic of using the ProcessBuilder, from what I've researched, is that we initiate the cmd first, then send "cd ..." as a subprocess or inputstream, and do the same with the desired commands.. So I haven't tried this. I don't know how to.

    Also I recently found out about another possible solution: System.setProperty("user.dir", String Location);. I am not sure if its a variable from JVM or CMD. What this basically does is change is the directory (the directory that specifies where a .class file is located before executing it through the cmd). My logic is I could change this variable before compiling or executing the next program. I've tried it however I am getting:

    C:\Users\Andrew\Desktop\Wish List>java Mercury
    Was file C:\rmwtdvm.java created ? : true
    Was file C:\rmwtdvm.java written ? : true
    Current working directory: C:\
    javac rmwtdvm.java stderr: javac: file not found: rmwtdvm.java
    javac rmwtdvm.java stderr: Usage: javac <options> <source files>
    javac rmwtdvm.java stderr: use -help for a list of possible options
    javac rmwtdvm.java exitValue() 2
    java rmwtdvm stderr: Error: Could not find or load main class rmwtdvm
    java rmwtdvm exitValue() 1
    I've placed some S.O.P.s so I'd be able to determine if user.dir was changed, and I can see it did. However java was not able to find the file. I am using Runtime getRuntime() exec(String command) to run the desired commands assuming the user.dir value was changed. But apparently it did not work. Maybe user.dir value is being reset by Runtime getRuntime() exec(String command)? Maybe user.dir is not used by the Runtime getRuntime() exec(String command)? I don't know that. I still think I could test some other things.

    Finally, what other people say is this: Java Applications and the "Current Directory" , unfortunately.

    the code is the following:

    [highlight=java]import java.io.*;
    import java.util.*;

    // Code Removed //


    Key Points of Assistance

    1. Please don't tell me to give up, or to try something different.
    2. Could you briefly explain the ProcessBuilder or any comments on it.
    3. Maybe you've got some knowledge about the user.dir you'd like to share.
    4. Any other function I could try?


    --- Update ---

    I forgot to say, I thank all the people that has been helping me out with this problem. I do appreciate it. I been receiving great support from this community to get this project of mine going.


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    Your problem is pretty specific, so in the future I'd recommend eliminating all that extra code.

    In fact, your actual problem has nothing to do with code- you're trying to compile from a different directory. That's fine, but you have to give the compiler the path of the file to compile. If you're confused about where the current directory is, try creating a new File("") and printing out its absolute path. Then go to that location with a command line and try to compile the class yourself. I think you'll get a similar error, because you aren't giving the right path to the java file.

    I've put together a little example that creates a new .java file, then uses a ProcessBuilder to compile and run it:

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.lang.ProcessBuilder.Redirect;
     
    public class Main {
     
    	public static void main(String... args) throws IOException, InterruptedException{
     
    		//create .java file
    		File f = new File("C:\\Users\\kworkman\\Desktop\\Test.java");
    		f.createNewFile();
    		PrintWriter out = new PrintWriter(new FileWriter(f));
    		out.println("public class Test{");
    		out.println("public static void main(String... args){");
    		out.println("System.out.println(\"HERE\");");
    		out.println("javax.swing.JOptionPane.showMessageDialog(null, \"HERE\");");
    		out.println("}}");
    		out.flush();
    		out.close();
     
    		//compile it
    		ProcessBuilder pb = new ProcessBuilder("javac", "C:\\Users\\kworkman\\Desktop\\Test.java");
    		File log = new File("log");
    		pb.redirectErrorStream(true);
    		pb.redirectOutput(Redirect.appendTo(log));
    		Process p = pb.start();
    		p.waitFor();
     
    		//run it
    		pb = new ProcessBuilder("java", "-cp", "C:\\Users\\kworkman\\Desktop", "Test");
    		pb.redirectErrorStream(true);
    		pb.redirectOutput(Redirect.appendTo(log));
    		p = pb.start();
    		p.waitFor();
     
    		System.out.println("Done.");
    	}
    }

    By the way, this is exactly the type of stuff lisp was built for.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #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: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    Thank you KevinWorkman.

    I will test the demo and try it on on program.

    P.S. lisp? Nvm I'll google it.

    --- Update ---

    I thank you so much.

    I've got a couple of questions actually.

    So I did not know about the "out.println();" which is much more efficient, than what I was previously doing.
    Also when the ProcessBuilder is initialized with two params you are able to send instruction and location.
    I am not sure why you use "File log = new File("log");" though. I am assuming "log" is some kind of abstract file that keeps record of the errors generated by the ProcessBuilder. I don't see that you are using try catch, why is that?
    So the ProcessBuilder is just to create the instructions, and the Process executes the instructions of the ProcessBuilder.
    And may I ask why are you using waitFor(); What are we exactly waiting on?

    * Also, does it make a difference to have main(String... args) and not main(String[] args) ?

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    Quote Originally Posted by Andrew R View Post
    I am not sure why you use "File log = new File("log");" though. I am assuming "log" is some kind of abstract file that keeps record of the errors generated by the ProcessBuilder.
    You're reading too much into this. The log is simply a file named log (could be log.txt, whatever) that's created. If you open that file, you'll see the "HERE" that the second program prints out using System.out.println(), as well as any errors the second program generated. It's just an easy way to contain the output of the second program.

    Quote Originally Posted by Andrew R View Post
    I don't see that you are using try catch, why is that?
    Because I'm lazy. This is an example program that just shows the basics. A real program would probably use more advanced error handling.

    Quote Originally Posted by Andrew R View Post
    And may I ask why are you using waitFor(); What are we exactly waiting on?
    Check out the API. The waitFor() method simply guarantees that the process has finished before continuing. I wouldn't want to try to run a class file before the compiler has finished creating it.

    Quote Originally Posted by Andrew R View Post
    * Also, does it make a difference to have main(String... args) and not main(String[] args) ?
    Nope. Just different ways to declare an array. The ... is something called varargs if you want to look it up.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. The Following User Says Thank You to KevinWorkman For This Useful Post:

    Andrew R (August 14th, 2013)

  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: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    I thought managing the exceptions is must, but guess thats only if the main doesnt throw anything.

    I can take it from this point foward.

  7. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    Quote Originally Posted by Andrew R View Post
    I thought managing the exceptions is must, but guess thats only if the main doesnt throw anything.
    If you call a function that might throw an Exception, you either have to put it in a try/catch block or throw the exception yourself. It's generally a bad idea to simply ignore them and throw them all the way back to main, but I'm just trying to show you the basics. Recommended reading: Lesson: Exceptions (The Java™ Tutorials > Essential Classes)
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  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: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    Hey Kevin,

    I've been managing the exceptions thrown out, and I was attempting not to use the log, but send all output and exceptions to a String I later assign a method to retrieve it.

    It seems that I messed up somewhere and the new .java file is not being compiled, but at least is being saved.

  9. #8
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    Quote Originally Posted by Andrew R View Post
    Hey Kevin,

    I've been managing the exceptions thrown out, and I was attempting not to use the log, but send all output and exceptions to a String I later assign a method to retrieve it.

    It seems that I messed up somewhere and the .java is not being compile, but it is being saved.
    Please post your updated code in the form of an SSCCE- note that this should look more like my example instead of your whole program. Create a new project and only include the stuff directly related to the problem. Can you compile the created .java file manually?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  10. #9
    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: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    I am not ready to post my code yet.
    After reading over the internet, having an OutputStream converted to a String could be too challenging, I wouldn't have the patience.

    https://forums.oracle.com/thread/2097046:

    What do you want to achieve? Have the data that's beeing written to the OutputStream as a String?

    That'll be tricky, as a OutputStream usually handles binary data.

    So you either have to use a Writer (StringWriter) or have knowledge about the encoding of the data that is beeing sent to the OutputStream (in which case you could create a ByteArrayOutputStream and convert the resulting byte-array to a string).
    Ultimately what I want to achieve is to keep the concept of self-sufficient or "stand alone" concept to remain undiluted. In other words, I was looking for an option different from creating another file log.

    Obviously I've examined the option of .toString but I know its not "as is" but would return String representation of the output stream.

    At first I thought it would be fantastic to have the outputstream be managed as String (for practical purposes not relevant to the topic). But now, knowing I'd had to learn about the encoding, binary, and all, specially not knowing if this code could be useful for all OS shells I guess I rather just dump the output data from the process.

    So my next question, would be, how do I dump the output? Just save it in a temporal variable and not use it? Or if all, is it mandatory or necessary to make use of the output stream to have the rest of the program work?

    --- Update ---

    Another quick question is ProcessBuilder part of the lisp?

  11. #10
    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: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    I figured out what was the problem. Since new .java is ramdomly generated, I have to make sure that .java statement in it got the same name.

  12. #11
    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: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    I added this to the code:

    	ProcessBuilder deleteJava = new ProcessBuilder("del", f.getAbsolutePath());
            p = deleteJava.start();
    		processCheck(); //this just prints out errors from "p" process.
    	   p.waitFor();

    Now its showing this:

    C:\Users\Andrew\Desktop\Wish List>java Venus.java
    Error: Could not find or load main class Venus.java
    Great. *facepalm* I want to delete the .java that was created after the .class is created..

    --- Update ---

    Okay so I tried f.delete(); displaying same message.

    --- Update ---

    Ok never mind. Closed and open the command again. It worked.

  13. #12
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Cmd not recognizing a different Dir / ClassPath / FilePath / Environment

    Quote Originally Posted by Andrew R View Post
    I am not ready to post my code yet.
    We don't need, or even want, your full code. An SSCCE is the best way to go. For example, you seem to be asking about converting an OutputStream to a String- that has nothing to do with your other problems of creating a file. For that matter, where are you getting the OutputStream in the first place?

    Quote Originally Posted by Andrew R View Post
    Ultimately what I want to achieve is to keep the concept of self-sufficient or "stand alone" concept to remain undiluted. In other words, I was looking for an option different from creating another file log.
    You don't have to create a log file. You're getting too caught up in the specifics of my code. It was just an example. You can tweak it however you want, and you don't have to use a log file at all if you don't want to.





    Quote Originally Posted by Andrew R View Post
    So my next question, would be, how do I dump the output? Just save it in a temporal variable and not use it? Or if all, is it mandatory or necessary to make use of the output stream to have the rest of the program work?
    What happened when you tried?

    Quote Originally Posted by Andrew R View Post
    Another quick question is ProcessBuilder part of the lisp?
    Lisp is an entirely other language, which google should have told you.

    --- Update ---

    Quote Originally Posted by Andrew R View Post
    Now its showing this:
    C:\Users\Andrew\Desktop\Wish List>java Venus.java
    Error: Could not find or load main class Venus.java
    It doesn't make sense to pass a .java file into java. You pass .class files (without the .class part) into java.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. [SOLVED] Problem Multiple Commands and filepath or classpath.
    By Andrew R in forum What's Wrong With My Code?
    Replies: 7
    Last Post: August 11th, 2013, 06:55 AM
  2. Problem with code recognizing invalid characters after spaces....
    By Eclecstatic in forum What's Wrong With My Code?
    Replies: 4
    Last Post: September 22nd, 2012, 10:14 AM
  3. Eclipse not recognizing my method for class.
    By jerryg in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 9th, 2012, 06:52 PM
  4. [SOLVED] CLASSPATH environment variable
    By SPACE MONKEY in forum Java Theory & Questions
    Replies: 6
    Last Post: February 15th, 2011, 04:10 PM
  5. make dir using mkdir() in java io
    By mssi in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: May 6th, 2010, 04:51 PM

Tags for this Thread