【问题标题】:Eclipse shows errors when i write information in xml file当我在 xml 文件中写入信息时,Eclipse 显示错误
【发布时间】:2013-05-23 21:34:10
【问题描述】:

我使用 JDOM 库。当我将信息写入 xml 文件时,Eclipse 显示错误。该系统找不到指定的路径。我尝试在“语言”文件夹中创建文件。当我将信息写入此文件时,如何自动创建文件夹?我认为错误在这一行:

FileWriter writer = new FileWriter("language/variants.xml");

这是我的代码:

package test;

import java.io.FileWriter;
import java.util.LinkedList;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

class Test {
    private LinkedList<String> variants = new LinkedList<String>();

    public Test() {

    }
    public void write() {

        Element variantsElement = new Element("variants");
        Document myDocument = new Document(variantsElement);

        int counter = variants.size();
        for(int i = 0;i < counter;i++) {
            Element variant = new Element("variant");
            variant.setAttribute(new Attribute("name",variants.pop()));
            variantsElement.addContent(variant);
        }


        try {
            FileWriter writer = new FileWriter("language/variants.xml");
            XMLOutputter outputter = new XMLOutputter();
            outputter.setFormat(Format.getPrettyFormat());
            outputter.output(myDocument,writer);
            writer.close();
        }
        catch(java.io.IOException exception) {
            exception.printStackTrace();
        }
    }
    public LinkedList<String> getVariants() {
        return variants;
    }
}

public class MyApp {
    public static void main(String[] args) {
        Test choice = new Test();
        choice.write();
    }
}

这是错误:

java.io.FileNotFoundException: language\variants.xml (The system cannot find the path specified)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:104)
    at java.io.FileWriter.<init>(FileWriter.java:63)
    at test.Test.write(MyApp.java:31)
    at test.MyApp.main(MyApp.java:49)`enter code here

【问题讨论】:

    标签: java jdom-2


    【解决方案1】:

    顾名思义,FileWriter 用于写入文件。如果目录不存在,则需要先创建目录:

    File theDir = new File("language");
    if (!theDir.exists()) {
      boolean result = theDir.mkdir();  
      // Use result...
    }
    FileWriter writer = ...
    

    【讨论】:

      【解决方案2】:

      要创建目录,您需要使用 File 类的 mkdir()。 示例:

      File f = new File("/home/user/newFolder");
      f.mkdir();
      

      它返回一个布尔值:如果目录创建则返回 true,如果失败则返回 false。

      如果安全管理器存在并且它的 checkWrite() 方法不允许创建命名目录,mkdir() 也会抛出安全异常。

      PS:在创建目录之前,你需要使用exists()来验证这个目录是否已经存在,它也会返回布尔值。

      问候...

      777 先生

      【讨论】:

        猜你喜欢
        • 2013-06-25
        • 1970-01-01
        • 1970-01-01
        • 2015-01-18
        • 2021-12-28
        • 2018-08-09
        • 2012-09-22
        • 1970-01-01
        • 2013-12-05
        相关资源
        最近更新 更多