有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

写入新xsd文件时java FileNotFoundException

我使用DOMparser解析了一批XML模式文件。我接着添加了几个注释,这些注释对于我正在创建的应用程序是必不可少的。然后,我想将这些新的“预处理”文件写入一个新的位置,并得到一个FileNotFound异常(访问被拒绝)

下面是我编写文件的代码片段:

Transformer tFormer = TransformerFactory.newInstance().newTransformer();

// Set output file to xml
tFormer.setOutputProperty(OutputKeys.METHOD, "xml");

// Write the document back to the file
Source source = new DOMSource(document);
File preprFile = new File(newPath(xmlFile));
    // The newPath function is a series of String operations that result in a new
    relative path

try {
    // Create file if it doesn't already exist;
    preprFile.mkdirs();
    preprFile.createNewFile();
} catch (Exception e) {
    e.printStackTrace();
}

Result result = new StreamResult(preprFile);
tFormer.transform(source, result);

我得到的错误如下:

java.io.FileNotFoundException: absolutePathHere (Access is denied)

指向上述代码段中的这一行:

tFormer.transform(source, result);

我正在使用一台Windows机器(从某个地方读到可能是这个错误的根源),我已经尝试过关闭UAC,但没有成功

我在想,也许createNewFile()方法在创建文件后不会释放该文件,但找不到有关该文件的更多信息

希望StackOverflow能再次拯救我


共 (3) 个答案

  1. # 1 楼答案

    我找到了解决办法:

    File preprFile = new File(directory1/directory2/directory3/file.xsd);
    File directory = new File(directory1/directory2/directory3/);
    
    try {
    // Create file if it doesn't already exist;
        directory.mkdirs();
        preprFile.createNewFile();                              
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    谢谢你的帮助

  2. # 2 楼答案

    你说“目录已创建,文件似乎也已创建为目录”。所以我认为它会创建名为“wsreportkbo_messages”的目录。xsd'

    它给你的错误可能是因为你试图读取目录。您可以使用listFiles()列出目录中的文件

    无法打开和读取目录,请使用isFile()isDirectory()方法来区分文件和文件夹

  3. # 3 楼答案

    它可能是在一个没有该目录权限的用户帐户下运行的