gpt4 book ai didi

java - 可以在 java 程序中运行 java 类吗?

转载 作者:行者123 更新时间:2023-12-01 16:59:06 25 4
gpt4 key购买 nike

我一直在创建一个编写和运行 java 类的程序。到目前为止,我已经能够编写“Runable.java”类,但无法运行它。我尝试运行“runjava.bat”并让 .bat 运行“Runable.java”类,但我不断收到“错误:无法找到或加载主类 application.Runable.class”。我想知道我做错了什么,或者是否有更好的方法从 java 程序中运行 java 类?

这是我的代码(稍微简化):

Main.java:

package application;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

import javafx.application.Platform;
import javafx.stage.FileChooser;


public class Main {
final static String Program =
"package application;\n"
+ "public class Runable {\n"
+ "public static void main(String[] args) {\n"
+ "System.out.println(\"Hello\");\n"
+ "}\n"
+ "}\n";

public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
while(true){
System.out.println("State a comand.");
String Command = s.nextLine();
if (Command.equalsIgnoreCase("Write") || Command.equalsIgnoreCase("Save")){
FileChooser fileChooser = new FileChooser();

//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);

//Show save file dialog
File file = new File("src/application/Runable.class");

if(file != null){
SaveFile(Program, file);
}

}
else if (Command.equalsIgnoreCase("Run") || Command.equalsIgnoreCase("Play")){
ProcessBuilder builder = new ProcessBuilder(
"src/runjava.bat");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
else if (Command.equalsIgnoreCase("End") || Command.equalsIgnoreCase("Exit")){
Platform.exit();
}
else{
System.err.println("Command not recognized.");
System.err.println("Please try again.");
}
}

}

private static void SaveFile(String content, File file){
try {
FileWriter fileWriter = null;

fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}

}


}

runjava.bat:

javac "src\application\Runable.java"
java application.Runable.class

Runable.java(如果您没有从 Main.java 获取它):

package application;
public class Runable {
public static void main(String[] args) {
System.out.println("Hello");
}
}

最佳答案

java 命令需要类名,而不是文件名。除非你的类在“application.Runable”包中被称为“class”(它不是),否则你可能想使用:

java application.Runable

关于java - 可以在 java 程序中运行 java 类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29112981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com