当我在xml文件中写入信息时,Eclipse会显示错误

时间:2013-05-23 21:34:10

标签: java jdom-2

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

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

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

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

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

PS:在创建目录之前,您需要使用exists()返回布尔值来验证此目录是否已存在。

...问候

Mr.777