从 .jar 文件夹中读取文件
我需要以这种方式读取 jar 文件夹内的文件:
DataSource coverdata = new FileDataSource(new File("here is the path"));
如何获取确切的路径?我正在使用库,因此访问文件的唯一方法是 new File(),没有输入流。
I need to read the file, that is inside the jar folder in this way:
DataSource coverdata = new FileDataSource(new File("here is the path"));
How do I get the exact path? I am using a library, so the only way I can acces file is new File()
, no inputstreams.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
调用
ClassLoader.getResourceAsStream()::InputStream
或ClassLoader.getResource()::URL
。请参阅:
http ://download.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)
http://download .oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html#getResourceAsStream(java.lang.String)
包含所请求文件的 JAR 文件必须位于类路径中。
Call
ClassLoader.getResourceAsStream()::InputStream
orClassLoader.getResource()::URL
.See:
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html#getResourceAsStream(java.lang.String)
The JAR file containing the requested file must be in the classpath.
你走错路了。文件只是直接写入文件系统的东西。从 java API 的角度来看,jar 内的文件不是文件。
要读取此文件,您必须使用 JarInputStream 或 ZipInputStream 解析 JAR,找到感兴趣的条目并从输入流中读取。这并不难,但你必须写几行代码。
其他方法是使用 jakarta.org 中的 VFS 包。它为您提供不同文件系统、ZIP、TAR 和其他容器格式的元素的统一视图。
You are on the wrong way. File is only something that is directly written on file system. File inside jar is not a file from java API point of view.
To read this file you have to parse JAR using either JarInputStream or ZipInputStream, get to the interesting entry and read from the input stream. It is not hard to do but you have to write several lines of code.
Other approach is using VFS package from jakarta.org. It provides you unified view on elements of different files systems, ZIP, TAR and other container formats.
使用 @home 已经讨论过的 InputStream (getResourceAsStream() ) 方法创建一个新的临时文件,然后将其作为普通文件读取怎么样?
What about creating a new temporal file, with the InputStream (getResourceAsStream() ) methods that @home already talked about, and then reading it as a normal file?