从包的 src 文件夹中获取 xml 文件 [英] Getting xml file from src folder of the package

查看:31
本文介绍了从包的 src 文件夹中获取 xml 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前问过一个关于如何在stackoverflow上从xml导入文件的问题(阅读此处).提供给我的解决方案是使用

I have previously asked a question about how to import a file from xml on stackoverflow (Read here). The solution provided to me was to use

documentbuilder.parse( xmlhandler.class.getResourceAsStream("shutdownscheduler.xml")); 

这个解决方案是从"C:\Users\Rohan Kandwal\Documents\NetBeansProjects\Shutdown Scheduler\build\classes\shutdown\scheduler\shutdownscheduler.xml"这适用于只读目的.

This solution is picking the xml file from "C:\Users\Rohan Kandwal\Documents\NetBeansProjects\Shutdown Scheduler\build\classes\shutdown\scheduler\shutdownscheduler.xml"which is fine for read only purpose.

但我需要 documentbuilder 从位置访问文件 "C:\Users\Rohan Kandwal\Documents\NetBeansProjects\Shutdown Scheduler\src\shutdown\scheduler 以便我可以保存对 xml 所做的更新永久.有没有办法从 src 文件夹而不是 build 文件夹访问文件?

But i need documentbuilder to access file from location "C:\Users\Rohan Kandwal\Documents\NetBeansProjects\Shutdown Scheduler\src\shutdown\scheduler so that i can save updations made to the xml permanently. Is there a way to access file from src folder rather than build folder?

推荐答案

通常,当您的应用程序要写入文件时,它必须在具有写入权限的地方进行.您可以确定(在大多数情况下)您的应用程序将被允许具有此类访问权限的唯一地方是用户主目录.您可能已经注意到,其他基于 Java 的应用程序通常会在您的主文件夹中创建一个名为 ".some-application" 的目录(在您的情况下为 "C:\Users\Rohan Kandwal">).他们这样做的原因(其中之一)是写访问权限.

Usually when your application is supposed to write files it must do so in a place where it has write access. The only place where you can be sure (in most cases) that your app will be allowed to have such access is the user home directory. You might have noticed that other java based applications usually create a directory named ".some-application" in your home folder (in your case "C:\Users\Rohan Kandwal"). The reason (one of them) why they do so is write access.

你应该做同样的事情并且忘记使用 Class.getResourceAsStream(...) 来处理可写文件.您可以通过 System.getProperty("user.home") 获取您的主目录的路径.

You should do the same and forget about using Class.getResourceAsStream(...) for writeable files. You can get the path to your home directory via System.getProperty("user.home").

请注意,您的示例中使用的 Class.getResourceAsStream(...) 从您的 build 目录中获取文件的原因是因为您在其中运行它你骑.如果您在 IDE 之外运行它,则此路径将更改.这是因为类文件 (xmlhandler.class) 的路径很可能会发生变化,并且 Class.getResourceAsStream(...) 依赖它来查找资源.

Note taht the reason why Class.getResourceAsStream(...) as used in your example is getting a file from your build directory is because you are running it within your IDE. If you run it outside the IDE this path will change. This is because the path to the class file (xmlhandler.class) will most likely change and Class.getResourceAsStream(...) relies on it to find the resource.

另请注意,在部署应用程序时,您的 src 目录很可能甚至不存在.即使是这样,也无法知道您的用户是否会将其部署在具有写入权限的位置.所以你试图做的事情没有多大意义.

Also note that your src directory will most likely not even exist when the application is deployed. Even if it did, there's no way to know if your users will have it deployed in a location with write access. So what you are trying to do doesn't make much sense.

Edit01

这是一个如何做你想做的事的例子.这将为您的应用程序创建一个主目录,您可以在其中以任何方式写入文件.如果您要在应用程序运行之间保留的文件不存在,它将被创建并填充您的资源文件的内容.请注意,这只是一个示例.

This is an example of how you could do what you want. This will create a home directory for your application where you can write files any way you wish. If the file you want to preserve between application runs does not exist, it will be created and filled with the content of your resource file. Note that this is just an example.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ConfigDir {

    private static final String APP_DIR = ".myappdir";
    private static final String FILE_NAME = "shutdownscheduler.xml";

    private File fillFileFromTemplate(InputStream template, File file) throws FileNotFoundException, IOException {
            OutputStream out = null;
            try {
                out = new FileOutputStream(file);
                int read = 0;
                byte[] bytes = new byte[1024];
                while ((read = template.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                out.flush();
                return file;
            } catch (FileNotFoundException ex) {
                throw ex;
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }

    public static void main(String[] argv) throws IOException {        
        String userdir = System.getProperty("user.home"); // user home directory
        // OR if you know that your program will run from a directory that has write access
        // String userdir = System.getProperty("user.dir"); // working directory
        if (!userdir.endsWith(System.getProperty("file.separator"))) {
            userdir += System.getProperty("file.separator");
        }
        String myAppDir = userdir + APP_DIR;
        File myAppDirFile = new File(myAppDir);
        myAppDirFile.mkdirs(); // create all dirs if they do not exist
        String myXML = myAppDir + System.getProperty("file.separator") + FILE_NAME;
        File myXMLFile = new File(myXML); // this is just a descriptor        
        ConfigDir cd = new ConfigDir();        
        if (!myXMLFile.exists()) {
            // if the file does not exist, create one based on your template
            // replace "ConfigDir" with a class that has your xml next to it in src dir
            InputStream template = ConfigDir.class.getResourceAsStream(FILE_NAME);  
            cd.fillFileFromTemplate(template, myXMLFile);
        }

        // use myXMLFile java.io.File instance for read/write from now on
        /*
        DocumentBuilderFactory documentbuilderfactory=DocumentBuilderFactory.newInstance();
        DocumentBuilder documentbuilder=documentbuilderfactory.newDocumentBuilder();
        Document document=(Document)documentbuilder.parse(myXMLFile);
        document.getDocumentElement(); 
        ...
        */        
    }    
}

这篇关于从包的 src 文件夹中获取 xml 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆