[英]How would I go about reading from a packaged file?
I have a file that I packaged in my JAR file, but I can't figure out how I would read the text file and store it into a String variable. 我有一个打包在JAR文件中的文件,但是我不知道如何读取文本文件并将其存储到String变量中。 Any ideas anyone? 有任何想法吗?
This approach would work for any jar file, even if it's not in your current project/library/classpath: 这种方法适用于任何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存档中的资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.