簡體   English   中英

如何使用Java將xml文件保存到本地桌面

[英]How to save an xml file to local desktop in Java

我已經創建了一個xml文件,並且想要將其保存到桌面上,但是我不知道如何執行此類操作。

到目前為止,這是我的代碼:

// create xml
        DocumentBuilderFactory factory =
            DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document testDoc = builder.newDocument();

        Element bo = testDoc.createElement("bo");
        bo.setAttribute("type", "Employee");
        bo.setAttribute("id", emp.getId());
        testDoc.appendChild(bo);

        Element username = testDoc.createElement("username");
        username.setTextContent(emp.getUsername());
        bo.appendChild(username);

        Element passHash = testDoc.createElement("passwordHash");
        passHash.setTextContent(emp.getPasswordHash());
        bo.appendChild(passHash);

        Element passwordSalt = testDoc.createElement("passwordSalt");
        passwordSalt.setTextContent(emp.getPasswordSalt());
        bo.appendChild(passwordSalt);

        Element name = testDoc.createElement("name");
        name.setTextContent(emp.getName());
        bo.appendChild(name);

        Element lastLogin = testDoc.createElement("lastLogin");


        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("date = " + emp.getLastLogin());
        String date = df.format(emp.getLastLogin());
        lastLogin.setTextContent(date);
        bo.appendChild(lastLogin);

        DOMSource source = new DOMSource(testDoc);

        PrintStream ps = new PrintStream(emp.getId() + ".xml");
        StreamResult result = new StreamResult(ps);

        TransformerFactory transformerFactory = TransformerFactory
            .newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        transformer.transform(source, result);

謝謝,

您似乎已經確定要構建XML並將XML寫入文件,並且確實在詢問如何在用戶桌面上創建文件。

如果是這樣,請閱讀“ 在Windows下的Java中,如何找到重定向的桌面”文件夾中可接受的答案

順便說一句,該解決方案不是Windows特定的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM