我有以下的方法,其转换的源代码使用gvim作为HTML:Java进程WAITFOR
String code2html(String s) throws Exception {
if (s == null || s.length() == 0) return "";
String txtfile = "dummyFile"+(UUID.randomUUID().toString())+".txt";
String t;
//PrintWriter w = new PrintWriter(Konst.FPATH+"tmp.txt","UTF-8");
File fl = new File(Konst.FPATH+txtfile);
FileWriter fw = new FileWriter(fl);
PrintWriter w = new PrintWriter(fw);
w.println(s);
w.close();
Runtime rt = Runtime.getRuntime();
String T;
try {
// Process pr = rt.exec(T = "gvim -c \"set syntax=Java\" -c \"wq\" -c \"q\" "+Konst.FPATH+"tmp.txt");
//Process pr = rt.exec(T = "gvim "+Konst.FPATH+"tmp.txt -s "+Konst.FPATH+"scrip.vim");
Process pr = rt.exec(T = "gvim "+Konst.FPATH+txtfile+" -s "+Konst.FPATH+"scrip.vim");
System.out.println(T);
FileOutputStream fos;
StreamGobbler errorGobbler = new StreamGobbler(pr.getErrorStream(),"ERROR");
StreamGobbler outputGobbler = new StreamGobbler(pr.getInputStream(),"OUTPUT",fos=new FileOutputStream(Konst.FPATH+"garbage.out"));
errorGobbler.start();
outputGobbler.start();
fos.flush();
fos.close();
int exitVal = pr.waitFor();
StringBuilder sb = new StringBuilder();
//BufferedReader b = new BufferedReader(new FileReader(Konst.FPATH + "tmp.txt.html"));
if (exitVal == 0) {
BufferedReader b = new BufferedReader(new FileReader(Konst.FPATH + txtfile + ".html"));
while ((t = b.readLine()) != null && !(t.length() >= 5 && t.substring(0, 5).equals("<body"))) ;
do {
sb.append(t + "\n");
} while ((t = b.readLine()) != null && !(t.length() >= 6 && t.substring(0, 6).equals("</body")));
sb.append(t);
return sb.toString();
}
else return "";
}
catch (Throwable e) {
e.printStackTrace();
}
return "";
}
相关StreamGobbler是在这里:
class StreamGobbler extends Thread {
InputStream is;
String type;
OutputStream os;
StreamGobbler(InputStream is, String type) {
this(is,type,null);
}
StreamGobbler(InputStream is, String type, OutputStream os) {
this.is = is; this.type = type; this.os = os;
}
@Override
public void run() {
try {
PrintWriter pw = null;
if (os != null) {
pw = new PrintWriter(os);
}
InputStreamReader isr = new InputStreamReader(is);
BufferedReader r = new BufferedReader(isr);
String line = null;
while ((line = r.readLine()) != null) {
if (pw != null)
pw.print(line);
System.out.println(type + ">" + line);
}
if (pw != null)
pw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
因此,gvim的应该是源转换代码到一个名为dummy + random string.html的html文件。它是这样做的。只有当它涉及到BufferedReader读取文件时,它没有找到它(“没有这样的文件或目录”),虽然文件确实出现在相关的文件夹中。所以,显然该文件是在BufferedReader尝试访问后创建的,尽管有waitFor()命令。如何解决这个问题?
打印'Konst.FPATH + txtfile +“.html”'值并检查此路径是否正确 – Sanjeev
是的,这是正确的,文件出现在此路径中。 – Ilonpilaaja
尝试通过Thread.sleep检查退出值之前放一些延迟 – Sanjeev