Java 的文件路径或文件位置 - new file()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16313260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:15:38  来源:igfitidea点击:

File path or file location for Java - new file()

javafile-iofilepathreadxmlfile-location

提问by Joey

I have the following structure for my project.

我的项目具有以下结构。

In Eclipse:

在日食中:

myPorjectName
  src
    com.example.myproject
        a.java
    com.example.myproject.data
        b.xml

In a.java, I want to read b.xmlfile. How can I do that? Specifically, in a.java, I used the following code:

a.java,我想读取b.xml文件。我怎样才能做到这一点?具体来说,在 中a.java,我使用了以下代码:

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("data/b.xml"));

This code cannot find b.xml. However, if I change the path to src/com/example/myproject/data/b.xmlthen it works. The current location seems to be in the root of my project file.

此代码找不到b.xml. 但是,如果我将路径更改为 ,src/com/example/myproject/data/b.xml则它可以工作。当前位置似乎在我的项目文件的根目录中。

But I see other people's examples, if b.xmland a.javaare in the same folder, then we can directly use new File("b.xml").But I try putting b.xmlin the same folder of a.javarather than putting in the sub folder, but it still does not work. If this works, then in my case, I should be able to use new File("data/b.xml"), right? I really do not understand why this is not working.

但是我看别人的例子,如果b.xmla.java在同一个文件夹下,那么我们可以直接使用new File("b.xml"). 但是我尝试放在b.xml的同一个文件夹中a.java而不是放在子文件夹中,但它仍然不起作用。如果这有效,那么在我的情况下,我应该可以使用new File("data/b.xml"),对吗?我真的不明白为什么这不起作用。

采纳答案by NINCOMPOOP

If it is already in the classpath and in the same package, use

如果它已经在类路径和同一个包中,请使用

URL url = getClass().getResource("b.xml");
File file = new File(url.getPath());

OR , read it as an InputStream:

或者,将其读作InputStream

InputStream input = getClass().getResourceAsStream("b.xml");

Inside a staticmethod, you can use

static方法内部,您可以使用

InputStream in = YourClass.class.getResourceAsStream("b.xml");

If your file is not in the same package as the class you are trying to access the file from, then you have to give it relative path starting with '/'.

如果您的文件与您尝试从中访问该文件的类不在同一个包中,那么您必须为其提供以'/'.

ex : InputStream input = getClass().getResourceAsStream
           ("/resources/somex.cfg.xml");which is in another jar resource folder