如何在同一个方法中使用两个java.lang.Runtimes?

时间:2013-04-11 10:45:21

标签: java runtime.exec

我想在同一方法中使用两个Runtime。第二个使用第一个的结果。我返回两个文件(*.txt)的结果。第一个执行结果是正常的,但第二个文件是空的。

使用的代码如下:

public void applicationpackage() {
        try {
            Process process = Runtime.getRuntime().exec(
                    new String[] { "/bin/sh", "-c",
                            "ls " + pathPackage + "/*.apk" });
            process.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));
            File f = new File(pathPackage + "/packagename.txt");
            PrintWriter writer = new PrintWriter(f, "UTF-8");
            String line = reader.readLine();
            while ((line != null)) {
                System.out.println(line);
                applicationPackage.add(line);
                writer.println(line);
                line = reader.readLine();
                Process p = Runtime.getRuntime().exec(new String[]{
                        "/bin/sh", "-c", "cut -d. -f2,3 <<<" + line
                });
                p.waitFor();
                BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); 
                File file = new File(pathPackage +"/application.txt");
                PrintWriter w = new PrintWriter(file, "UTF-8");
                String l = r.readLine();
                while(l!= null){
                    w.println(l);
                    w.println("toto");
                    l = r.readLine();
                }

                name+= "cut -d. -f2,3 <<<" + line +" &";

                System.out.println("toto" + name);
            }
            System.out.println("toto" + name);
            writer.close();


        } catch (IOException | InterruptedException e1) { }

}

1 个答案:

答案 0 :(得分:0)

如果您的文件为空,通常表示您的PrintWriter未设置autoflush,或者您尚未关闭作者。对w的最后一次引用是w.println("toto");。将w.close()添加到您的代码中。

同样,当您实例化PrintWriter时,您应该在构造函数级别传入一个布尔值,以指示PrintWriter在每次操作后都应该刷新。