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

Joe*_*oey 10 java file-io readxml file-location filepath

我的项目有以下结构.

在Eclipse中:

myPorjectName
  src
    com.example.myproject
        a.java
    com.example.myproject.data
        b.xml
Run Code Online (Sandbox Code Playgroud)

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

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

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

但我看到其他人的例子,如果b.xmla.java是在同一个文件夹中,那么我们可以直接使用new File("b.xml").但我尝试放入b.xml相同的文件夹,a.java而不是放入子文件夹,但它仍然无法正常工作.如果这样可行,那么在我的情况下,我应该可以使用new File("data/b.xml"),对吧?我真的不明白为什么这不起作用.

NIN*_*OOP 20

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

URL url = getClass().getResource("b.xml");
File file = new File(url.getPath());
Run Code Online (Sandbox Code Playgroud)

或者,将其读作InputStream:

InputStream input = getClass().getResourceAsStream("b.xml");
Run Code Online (Sandbox Code Playgroud)

static方法内部,您可以使用

InputStream in = YourClass.class.getResourceAsStream("b.xml");
Run Code Online (Sandbox Code Playgroud)

如果您的文件与您尝试访问该文件的类不在同一个包中,则必须为其提供相对路径'/'.

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