对于 Class.getResouce(),双点符号不再适用于 classpth(使用 eclipse 时超出 bin)?
Double dot notation no longer works out of classpth (out of bin when using eclipse) for Class.getResouce()?
加载资源文件的一种常用方法是使用 Class.getResource(String name)
方法,该方法从应用程序的 classpath
搜索。
A FileReader
甚至可以使用双点符号从项目文件夹外的文件中读取。例如,使用 eclipse,你可以用 ../test.txt
读取 workspace/test.txt
。但是我在玩getResource()
方法的时候,只有在bin
文件夹下的文件才能得到双点符号的文件。如果将文件放在 bin
文件夹之外,双点符号将不再有效。我试图按照 ClassLoader.getResource()
、ClassLoader.parent.findResouce()
和 sun.misc.Launcher$AppClassLoader
的源代码,但无法进一步了解。这是在 windows 10.
我应该在这里添加一个示例。我在 eclipse 中有一个 test.txt 文件和 Java project1。
workspace/project1/src/package1/test.java
可以从
读取 test.txt 文件
workspace/test.txt
location with "../test.txt" with FileReader(eclipse 的默认位置似乎是 workspace/project1/)。但是对于 getResouce() ,只要文件放在 workspace/project1/bin 中而不是放在 bin 文件夹之外,双点符号就可以工作。
我对以上有一些疑问:
1,为什么双点符号不能用 getResouce()
将你带出 bin
文件夹,但用 FileReader
可以?
2,考虑到 getResouce()
的行为,我假设 eclipse 已成功将 bin
目录添加到项目 classpath
。在项目的 .classpath
文件中,还有一行:
<classpathentry kind="src" path="src"/>
难道src
文件夹没有添加到classpath
?因为 getResouce()
似乎没有在那里搜索。
why the double dot notation cannot bring you out of the bin folder with getResouce() but can do that with FileReader?
因为他们正在寻找不同命名空间中的文件。在 FileReader
的情况下,命名空间是文件系统命名空间,根目录是系统的根目录。在getResource()
的情况下,命名空间就是类路径对应的命名空间。该命名空间的顶部通常对应于类路径上的任何目录,以及类路径上任何存档的根索引。
无论哪种情况,您都不能使用“..”在命名空间顶部上方导航。
Does eclipse add the 'src' directory to the classpath too when the app is run locally with eclipse?
默认情况下,我认为答案是否定的。显然,您可以通过启动器配置属性更改它。
如果您想确定运行时类路径到底是什么,请打印出以下值:
System.getProperty("java.class.path")
加载资源文件的一种常用方法是使用 Class.getResource(String name)
方法,该方法从应用程序的 classpath
搜索。
A FileReader
甚至可以使用双点符号从项目文件夹外的文件中读取。例如,使用 eclipse,你可以用 ../test.txt
读取 workspace/test.txt
。但是我在玩getResource()
方法的时候,只有在bin
文件夹下的文件才能得到双点符号的文件。如果将文件放在 bin
文件夹之外,双点符号将不再有效。我试图按照 ClassLoader.getResource()
、ClassLoader.parent.findResouce()
和 sun.misc.Launcher$AppClassLoader
的源代码,但无法进一步了解。这是在 windows 10.
我应该在这里添加一个示例。我在 eclipse 中有一个 test.txt 文件和 Java project1。
workspace/project1/src/package1/test.java
可以从
读取 test.txt 文件workspace/test.txt
location with "../test.txt" with FileReader(eclipse 的默认位置似乎是 workspace/project1/)。但是对于 getResouce() ,只要文件放在 workspace/project1/bin 中而不是放在 bin 文件夹之外,双点符号就可以工作。
我对以上有一些疑问:
1,为什么双点符号不能用 getResouce()
将你带出 bin
文件夹,但用 FileReader
可以?
2,考虑到 getResouce()
的行为,我假设 eclipse 已成功将 bin
目录添加到项目 classpath
。在项目的 .classpath
文件中,还有一行:
<classpathentry kind="src" path="src"/>
难道src
文件夹没有添加到classpath
?因为 getResouce()
似乎没有在那里搜索。
why the double dot notation cannot bring you out of the bin folder with getResouce() but can do that with FileReader?
因为他们正在寻找不同命名空间中的文件。在 FileReader
的情况下,命名空间是文件系统命名空间,根目录是系统的根目录。在getResource()
的情况下,命名空间就是类路径对应的命名空间。该命名空间的顶部通常对应于类路径上的任何目录,以及类路径上任何存档的根索引。
无论哪种情况,您都不能使用“..”在命名空间顶部上方导航。
Does eclipse add the 'src' directory to the classpath too when the app is run locally with eclipse?
默认情况下,我认为答案是否定的。显然,您可以通过启动器配置属性更改它。
如果您想确定运行时类路径到底是什么,请打印出以下值:
System.getProperty("java.class.path")