【发布时间】:2011-11-02 09:49:44
【问题描述】:
我有一个打包在 JAR 文件中的文件,但我不知道如何读取文本文件并将其存储到字符串变量中。 有什么想法吗?
【问题讨论】:
-
“有什么想法吗?” 1. 完成教程的Basic I/O lesson。 2. 在提问之前表现出一些努力。你试过什么?你被困在哪里了?等
我有一个打包在 JAR 文件中的文件,但我不知道如何读取文本文件并将其存储到字符串变量中。 有什么想法吗?
【问题讨论】:
这种方法适用于任何 jar 文件,即使它不在您当前的项目/库/类路径中:
String myJarFilename ="C:\\path\\to\\myfile.jar";
JarFile jarFile = new JarFile(myJarFilename);
JarEntry jarEntry = jarFile.getJarEntry("mytextfile.txt");
if (jarEntry != null)
{
InputStream is = jarFile.getInputStream(jarEntry);
// do normal stuff here to read string from inputstream
InputStreamReader isr = new InputStreamReader(is);
byte[] charArr = new byte[2048];
int bytesRead = 0;
StringBuffer sb = new StringBuffer();
while (bytesRead = is.read(charArr, 0, 2048) > 0)
{
sb.append(charArr, 0, bytesRead);
}
String fileContent = sb.toString();
}
【讨论】:
您可以使用 URLClassLoader 访问 JAR 存档中的资源。
【讨论】: