如何在java中执行java文件
我想在服务器端编译和运行java文件,并在客户端查看输出,这样当要求输入时,程序员可以提供。 到目前为止,我已经使用Java编译器API来编译Java代码 代码如下:如何在java中执行java文件,java,Java,我想在服务器端编译和运行java文件,并在客户端查看输出,这样当要求输入时,程序员可以提供。 到目前为止,我已经使用Java编译器API来编译Java代码 代码如下: public class CompileCode extends Thread { File javafile,errorfile; String parameters; String compileoutput; File err; public CompileCode(File f,String parameters)
public class CompileCode extends Thread {
File javafile,errorfile;
String parameters;
String compileoutput;
File err;
public CompileCode(File f,String parameters)
{
javafile = f;
this.parameters=parameters;
err=new File("Errors.txt");
}
@Override
public void run()
{
try{
FileOutputStream errorstream=new FileOutputStream(err);
FileInputStream inputstr=new FileInputStream(out);
JavaCompiler compilerinstance=ToolProvider.getSystemJavaCompiler();
int compileresult=compilerinstance.run(null, null, errorstream,javafile.getAbsolutePath());
errorstream.close();
out.close();
if(compileresult==0)
{
compileoutput="Compilation Successful";
}
else
{
compileoutput="Compilation failed";
}
}
catch(IOException ex1)
{
System.out.println(ex1.getMessage());
}
}
public String getOutMessage()
{
return compileoutput;
}
public String getErrorlog()
{
String output=" ",line=" ";
StringBuffer sb=new StringBuffer();
try{
BufferedReader br =new BufferedReader(new FileReader(err));
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
output=sb.toString();
}
catch(Exception ex2)
{
System.out.println(ex2.getMessage());
}
finally
{
return output;
}
}
}
读取输出的代码为:
ProcessBuilder pb =new ProcessBuilder("java ",filename);
pb.directory(fl.getParentFile());
pb.redirectError();
Process p = pb.start();
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuffer sb=new StringBuffer();
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
line=sb.toString();
Outmessage=Outmessage.concat(line);
p.waitFor();
其中fl是.java文件,filename是不带扩展名的文件名
发生的异常是:
java.io.IOException: Cannot run program "java -cp . " (in directory "C:\Users\Mayank"): CreateProcess error=2, The system cannot find the file specified
可能系统找不到指定文件的错误消息给出了提示?您应该将完整路径添加到可执行文件中。我确实为ex.Example.java添加了完整路径,它存储在C:\Users\Mayank中。我添加了filename=C:\Users\Mayank\Example,但它仍然显示相同的错误您是否真的在或认为在目录C:\Users\Mayank中有java.exe?提示:我说的是可执行文件。您正在调用可执行文件。这就像问你的操作系统:嘿,请为我启动“java”。请看以下链接: