简体   繁体   中英

How to change path while running java file?

I am trying to run a java file through another java program . this is my 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());
      }

      public static void main(String[] args) {
          String[] credentials=new String[4];int k=0;
          for (String s: args) {
              System.out.println(s);
            credentials[k]=s;k++;
        if(k==4)
        break;
          }
        try {
          //runProcess("javac test2.java");
          runProcess("java test2 "+credentials[0]+" "+credentials[1]+" "+credentials[2]+" "+credentials[3]+" ");

        } catch (Exception e) {
          e.printStackTrace();
        }System.out.println("hI");
      }

The problem is I have kept both the files(which I execute and the one which is executed by that file) in same folder but when I run this file it displays class not found error.. for test2.java and it probably due to the fact that it searches the class file test2.class in some other folder . what should I do? my file structure:
x/y/Laj.java
x/y/test2.java
and it seaches the class file in x folder?

Use

Runtime.getRuntime().exec(command, null, workingDir);

where workingDir is :

workingDir- the working directory of the subprocess, or null if the subprocess should inherit the working directory of the current process.

If you run the first program using

java x.y.Laj

then you should change the line where you compose the command:

runProcess("java x.y.test2 "+credentials[0]+...

** Later **

Since the xy is just a red herring, try setting the system property:

runProcess("java  -Djava.class.path=\"/.../x/y\" " + credentials[0]+...

For production (start of Laj not from an IDE) consider setting CLASSPATH so that all class files can be found via the class path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM