Java命令错误。无法找到或加载主类

时间:2017-07-17 21:18:11

标签: java intellij-idea

今天我遇到了" java"命令。 我在Intellij IDEA工作,并认为我错误的类路径到" java"命令。 求你帮帮我。

package ru.mch;
import ru.mch.RunTask;

public class Program {
    public static void main(String[] args) {
        String taskCode = "class UserProgram{ public static void main(String[] args) { int b = 3 + 1; System.out.println(b);}}";
        String packageName = "package ru.mch; ";
        String all = packageName + taskCode ;
        RunTask runTask = new RunTask(all);
        int result = runTask.run();
    }
}

我想从String获取程序代码,创建新的java类,将代码写入类并编译和运行新的java类。

package ru.mch;
import java.io.*;

public class RunTask {

    private String answerFromPage;
    private int programExitValue;

    public RunTask(String answerFromPage) {
        this.answerFromPage = answerFromPage;
        this.programExitValue = 0;
    }

    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(line);
        }
    }

    private static int runProcess(String command) throws Exception {
        Process pro = Runtime.getRuntime().exec(command);
        printLines(/*command + */" stdout:", pro.getInputStream());
        printLines(" stderr:", pro.getErrorStream());
        pro.waitFor();
        System.out.println(command + " exit value = " + pro.exitValue());
        return pro.exitValue();
    }

    public int run(){
        //String fileName = "src\\main\\java\\ru\\mch\\UserProgram.java";
        String fileName = "src\\main\\java\\ru\\mch\\UserProgram.java";
        File f = new File(fileName);
        f.getParentFile().mkdirs();
        try {
            f.createNewFile();
        } catch (IOException e) {
            throw new IllegalArgumentException("File creating error");
        }
        try(FileWriter writer = new FileWriter(fileName, false))
        {
            writer.write(this.answerFromPage);
            writer.flush();
        }
        catch(IOException ex){
            System.out.println(ex.getMessage());
        }
        try {
            System.out.println(runProcess("javac -sourcepath src src\\main\\java\\ru\\mch\\UserProgram.java"));
            System.out.println("------------");
            this.programExitValue = runProcess("java src\\main\\java\\ru.mch.UserProgram");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this.programExitValue;
    }
}

这是IDEA日志:

javac src\main\java\ru\mch\UserProgram.java exit value = 0
0
------------
Error: Could not find or load main class src\main\java\ru.mch.UserProgram
java src\main\java\ru.mch.UserProgram exit value = 1

创建了新类,也创建了.class。 我尝试编写完整的类路径,尝试编写' \'而不是'而不是'在包名中,但都错了。 抱歉我的英语不好。

1 个答案:

答案 0 :(得分:0)

使用以下命令:

java -cp src\main\java ru.mch.UserProgram