使用Java

时间:2016-12-07 12:27:47

标签: java xml xslt

我正在尝试使用java将XML文件转换为CSV格式,并将结果放在一个新目录中,并以当前日期和小时作为名称。我是Java新手,直到现在我才刚刚成功创建目录并进行转换。任何人都可以告诉我如何正确地执行此操作,以便转换后的文件将自动进入创建的目录?谢谢您帮忙。 这是我到目前为止使用的代码:

    public static void main(String args[]) throws Exception {


        // Creating new directory in Java, if it doesn't exists

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");


        boolean success = false;
        // String time = dateFormat.format(date);
        String dir = "P:/export/";

        File directory = new File(dir + dateFormat.format(date));
        if (directory.exists()) {
            System.out.println("Directory already exists ...");

        }
        else {
            System.out.println("Directory not exists, creating now");

            success = directory.mkdir();
            directory.createNewFile();
            if (success) {
                System.out.printf("Successfully created new directory : %s%n", dir);
            }
            else {
                System.out.printf("Failed to create new directory: %s%n", dir);
            }
        }

        String AppDir = "P:/XML/";

        File stylesheet = new File(AppDir + "xsl/newTest.xsl");
        File xmlSource = new File(AppDir + "import/Tests/newTest.xml");

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(xmlSource);

        StreamSource stylesource = new StreamSource(stylesheet);
        Transformer transformer = TransformerFactory.newInstance()
                                                    .newTransformer(stylesource);
        Source source = new DOMSource(document);
        Result outputTarget = new StreamResult(new File(AppDir + "export/newTest.csv"));
        transformer.transform(source, outputTarget);
    }
}

1 个答案:

答案 0 :(得分:2)

AppDir变量值更改为指向新目录,如下所示:

String AppDir = directory.getAbsolutePath() + File.seperator + XML + File.seperator;

通过这种方式,您的所有XML文件将进入新创建的目录,然后进入XML文件目录。

相关问题