我有一个程序使用runtime.exec()来编译和运行代码java。我把代码需要用程序运行到不同的目录中。代码有方法从文件读取整数,所以当我运行程序编译并在目录中运行代码java然后有错误是找不到文件。 谁可以帮助我通过cmd运行代码java或使用runtime.exec(命令)执行代码java从文件中读取数据?
这是programe和代码java需要运行。
import java.io.*;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class TestCodeJava {
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);
BufferedReader reader = new BufferedReader(new InputStreamReader(pro.getInputStream()));
pro.waitFor();
String line = "";
while((line = reader.readLine())!=null)
{
System.out.println(line);
}
}
private static int toCompile(String fileToCompile)
{
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, "-verbose", fileToCompile);
return compilationResult;
}
public static void main(String[] args) {
try {
if(toCompile("E:\\Folder\\Prime.java")==0)
{
runProcess("java -cp \"E:\\Folder\" Prime");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
public class Prime {
private static boolean isPrime(int n)
{
if(n <= 1) return false;
if(n == 2 || n == 3) return true;
int m = (int) Math.sqrt(n);
for(int i = 5; i <= m; i = i + 5)
if(n % i == 0 || n % (i+2) == 0) return false;
return true;
}
public static void main(String args[]) throws FileNotFoundException, IOException
{
File file = new File("INPUT.TXT");
FileInputStream fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
int n = Integer.parseInt(reader.readLine());
File file2 = new File("OUTPUT.TXT");
FileOutputStream fos = new FileOutputStream(file2);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
if(isPrime(n))
{
writer.write("YES");
}else writer.write("NO");
writer.flush();
writer.close();
}
}