1

I'm working on a program (with JavaSE 1.6) that will read from text files located in the project's classpath.

The files are in a different folder than the class that's trying to access them, though, and directing my code to their location is baffling me.

The class I'm running is located in a package in the "src/test/java" folder, while the text files are separated into multiple folders (for organizational purposes) within the "src/main/resources" folder.

I'm currently trying to point to the text files using the following code, but after the line runs, 'in' receives a null value:

InputStream in = this.getClass().getResourceAsStream("/src/main/resources/<folder name here>/<file name here>.txt");

I'm not sure if I'm allowed to specify the file like this if it's in a different directory, so I'm a bit lost on how to proceed...I've searched Google and StackOverflow and found plenty of resources for reading files from the classpath but nothing about how to point the InputStream to a file outside of the class' package. Can anyone please tell me whether or not it's possible and, if so, how it can be done?

4

4 回答 4

3

实际答案完全取决于您如何构建/打包它。

看起来像一个 Maven 项目,在这种情况下,src/xxx/yyy文件夹不在您的实际类层次结构中。构建后,src/main/resources将位于类路径的根目录,这意味着类路径资源只是your/folders/and/file.txt.

如果它不是一个 Maven 项目,那么它取决于你如何构建它。

于 2013-05-23T15:19:22.643 回答
1

对于同一个罐子,这个:

InputStream in = this.getClass()
    .getResourceAsStream("/<folder name here>/<file name here>.txt");

这可以使用相对于类的包的相对路径,但在这里它是绝对的。

这将执行以下操作(考虑 Maven 构建):

  • 下面的源文件src/main/resources/<folder-path>/<file>通常被复制到target/classes/<folder-path>/<file>. IDE 通常使用此路径进行内部运行。
  • 在构建时,会在/target/<project>.jar.
  • 用 7zip/WinZip 打开那个 jar 会显示<folder-path>/<file>.

运行 jar 重要的是路径区分大小写。

如果资源在另一个目录中

然后使用 SystemClassLoader(具有所有类路径)。

InputStream in = ClassLoader
    .getSystemResourceAsStream("<folder name here>/<file name here>.txt");

这使用我认为的绝对路径。这种用法可能会受益于具有(单个?)META-INF/INDEX.LIST(覆盖多个罐子)的罐子。

于 2013-05-23T15:30:02.747 回答
1

/src从你的路径中删除。假设src在您的构建路径上(在您的 IDE 中),那么编译后的代码将仅包含其中的文件夹,直接位于根目录下。例如,

/src
    /main/resources
        file.txt

会产生

/main/resources/file.txt

现在,如果/src/main/resources在构建路径中,您需要删除整个内容,该文件将出现在根目录中。它InputStream可以作为

InputStream in = this.getClass().getResourceAsStream("/<folder name here>/<file name here>.txt");

例子

/src/main/resources  // buildpath
    /spring
        applicationContext.xml
/src/main/java  // buildpath
    /mypackage
        MyClass.java

可以像

InputStream in = this.getClass().getResourceAsStream("/spring/applicationContext.xml");

这意味着 jar(如果这是您编译和打包它的方式)将被构造为

/spring
    applicationContext.xml
/mypackage
    MyClass.class

方法getResourceAsStream(String) javadoc说:

  • 如果名称以“/”开头(“\u002f”),则资源的绝对名称是名称中“/”后面的部分。
  • 否则,绝对名称的格式如下:
    modified_pa​​ckage_name/name

其中 modified_pa​​ckage_name 是此对象的包名称,其中 '/' 替换为 '.' ('\u002e')。

于 2013-05-23T15:17:37.203 回答
0

通常, src 不在您的类路径中。更改类目录下相应文件的路径。

于 2013-05-23T15:17:14.403 回答