【问题标题】:How would I go about reading from a packaged file?我将如何从打包文件中读取?
【发布时间】:2011-11-02 09:49:44
【问题描述】:

我有一个打包在 JAR 文件中的文件,但我不知道如何读取文本文件并将其存储到字符串变量中。 有什么想法吗?

【问题讨论】:

  • “有什么想法吗?” 1. 完成教程的Basic I/O lesson。 2. 在提问之前表现出一些努力。你试过什么?你被困在哪里了?等

标签: java file jar package


【解决方案1】:
【解决方案2】:

这种方法适用于任何 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();
}

【讨论】:

  • 您(或某人)能否简要说明如何将整个文件存储到字符串变量中?
  • 嵌入的文本文件还是 Jar 文件?
  • 请嵌入文本文件
  • 好的,我粗略地编写了从 InputStream 读取文件的代码。可能不是 100% 完美,但会给你灵感。
【解决方案3】:

您可以使用 URLClassLoader 访问 JAR 存档中的资源。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-07
    • 2017-04-25
    • 2011-08-27
    • 2018-11-07
    • 1970-01-01
    • 2017-06-06
    • 2013-11-20
    相关资源
    最近更新 更多