所以昨天在 StackOverflow 的一些帮助下得到了赞赏,太糟糕了,我还不能投票。好吧,我能够从一个 Java 程序中创建一个 Java 程序,这让我更接近于让我进入计划中真正困难的部分。
所以现在正如标题所述,我有这段代码,我正在尝试用它来执行另一个 java 程序,但到目前为止,我尝试过的一切都失败了。我现在有多个文件,没有错误,只是没有任何反应,没有任何打开。两者都有 Runtime.getRuntime().exec(); 和 ProcessBuilder = new ProcessBuilder(); 我也想知道我可以只执行 .jar 文件还是也可以编译和执行 .java 文件?如果有怎么办?因此,是的,任何有关出现问题的帮助将不胜感激。
谢谢你。
编辑:更新了代码,我似乎越来越接近它的工作了。这些目录现在似乎可以工作了。只是我得到了内置的错误系统回复它找不到Java -Jar
我到目前为止的代码可以在下面阅读:
import java.io.File;
import javax.swing.JOptionPane;
public class SelfWrite {
public static void main(String args[]) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
try {
String newLine = new String(System.getProperty("line.separator"));
File f = new File("C:/Users/Powermaniac/workspace/Newfolder/");
String fileDir = new String (f.getAbsolutePath());
File j = new File("C:/Windows/System32/java" + "-jar");
String javaDir = new String(j.getAbsolutePath());
File tempDir = new File (fileDir);
File tempjavaDir = new File (javaDir);
if (tempDir.exists());
JOptionPane.showMessageDialog(null, "File Exists");
if (tempjavaDir.exists());
JOptionPane.showMessageDialog(null, "Java Exists");
if (tempDir.exists()) {
String program = new String(fileDir + "UserInput.jar");
try {
ProcessBuilder pb = new ProcessBuilder("C:/Windows/System32/java", "-jar", program);
pb = pb.directory(new File(fileDir));
File temp = pb.directory();
String currentWorkingDirectory = "Current working directory: " + temp.toString();
JOptionPane.showMessageDialog(null, currentWorkingDirectory);
Process p = pb.start();
int UserInputExitCode = p.waitFor();
if (UserInputExitCode == 0) {
JOptionPane.showMessageDialog(null, "User Input Running Successfully!");
}
else {
JOptionPane.showMessageDialog(null, "User Input Exit Code: " + UserInputExitCode +
newLine + "Something went awry during UserInput.jar execution!");
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, "User Input installation failed!" + newLine +
"Couldn't find \"Java -Jar\" in the Standard Software directory.");
}
}
else {
JOptionPane.showMessageDialog(null, "Can't find the Java -Jar directory!" +
newLine + "Program will now exit.");
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Something has gone awry while running the processbuilder class!");
}
}
}