从 jar 中高效提取文件
我有一个用 Java 编写的应用程序,它使用一个 jar 文件(它使用多个 jar 文件,但这不是重点)。
事实上,我正在使用的 Jar 文件包含我绝对必须提取到文件系统的文件。
到目前为止,我正在使用 Class.getResourceAsStream 和 FileOutputStream,但这种方法有点慢。 请注意,其中一些文件是基于文本的,但其他文件只是二进制文件。
那么,除了尝试减少从 JAR 中提取文件的需要之外,是否有针对这些任务的任何优化(例如更充分的功能)。
请注意,我的应用程序是基于 Java 6 的,我希望将外部依赖项减少到最低限度。
编辑:为了将来的参考,我的旧(效率低下)代码是:
int c;
while((c = is.read())!=-1){
fos.write(c);
}
对于新的、更快的代码,请参阅已接受的回复。
I have an application written in Java that uses a jar file(it uses more than one, but that's not the point).
The fact is, the Jar file I'm using contains files that I absolutely MUST extract to the filesystem.
So far I'm using Class.getResourceAsStream and FileOutputStream, but this method is somewhat slow.
Note that some of these files are text-based, but others are simply binary.
So apart from trying to reduce the need to extract files from JARs, are there any optimizations(such as more adequated functions) for these tasks.
Note that my application is Java 6-based and I would like to reduce external dependencies to a minimum.
EDIT: For future reference, my OLD(inefficent) code was:
int c;
while((c = is.read())!=-1){
fos.write(c);
}
For the new, much faster code, see the accepted reply.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以控制 jar 文件吗? 如果您以未压缩的方式创建它,可能会使其速度更快。 显然,它会使 jar 文件变得更大...
另一件事要检查 - 你如何提取文件? 例如,如果您逐字节进行操作,速度会非常慢。 使用这样的内容:
如果您已经这样做了,您能给我们更多信息吗? “有点慢”有多慢? 与使用 jar 实用程序提取 jar 文件相比如何?
Do you have control over the jar file? If you create it uncompressed, that may make it faster. Obviously it'll make the jar file bigger though...
Another thing to check - how are you extracting the file? For instance, if you're doing it byte by byte it will be painfully slow. Use something like this:
If you're already doing this, could you give us more information? How slow is "somewhat slow"? How does it compare with, say, using the jar utility to extract the jar file?
呃。 我不确定您真正想要做什么 - 但您是否考虑过使用 winzip?
显然,如果您需要在运行时动态提取文件,这将不起作用 - 但我不确定为什么您需要这样做 - 这个 jar 文件多久更改一次?
您当然可以提取它们一次,然后将它们与应用程序一起分发吗?
Err. I'm not sure what you really want to do - but have you thought about using winzip?
Obviously if you need to extract the files dynamically at run time this won't work - but I'm not sure why you'd need to do this - how often does this jar file change?.
Surely you can extract them once and then distribute them with the application?
我同意乔恩的观点。 有两件事可以使提取速度更快:
我认为需要提取是由于需要从文件中写入/重新读取。 如果文件足够小,内存足够大,并且文件的持久性不是必需的; 您可能会考虑将整个资源映射到内存,而不是使用磁盘作为存储。
I concur with Jon. 2 things will make extraction faster:
I am supposing the need to extract is due to a requirement to write/re-read from the file. If the files are small enough, memory is large enough and the persistent nature of files isn't a requirement; you might consider mapping the entire resource to memory instead of using the disk as storage.