如何在windows中写入和读取文件到临时文件夹

时间:2014-08-13 05:45:18

标签: java graphviz

我使用graphviz将代码解析为树形图像。您知道,Graphviz是读取文件然后写入文件图像。那么,如何将该文件写入Windows中的临时文件夹,然后再次读取该文件。这是我的代码:

     DOTTreeGenerator gen = new DOTTreeGenerator();
     StringTemplate st = gen.toDOT(tree);

     String OS = System.getProperty("os.name");
     Runtime rt = Runtime.getRuntime();


            try {

                File file = new File("D:\\workspace\\output.dot"); // create a file
                BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
                bw.write(st2);
                bw.close();


                String dotPath = "C:\\Program Files (x86)\\Graphviz2.38\\bin\\dot.exe";
                String fileInputPath = "D:\\workspace\\output.dot";
                String fileOutputPath = "D:\\workspace\\treeImage.png";
                String tParam = "-Tpng";
                String tOParam = "-o";

                String[] cmd = new String[5];
                cmd[0] = dotPath;
                cmd[1] = tParam;
                cmd[2] = fileInputPath;
                cmd[3] = tOParam;
                cmd[4] = fileOutputPath;

                rt.exec(cmd);

            } catch (IOException ex) {
                System.out.println("Failed to write to file");
            }
        }

2 个答案:

答案 0 :(得分:1)

使用File.createTempFile ,这将正确处理所有具有JVM的操作系统的所有临时目录。

答案 1 :(得分:0)

您可以像这样获得os临时目录路径:

    String tempPath = System.getProperty("java.io.tmpdir");
    File tempFile = new File(tempPath + File.separator + "myTempFile.dat");
    // todo read/write file