0

我迭代了一些我知道是文本文件的 JarEntries。但是当我找到它时如何将 JarEntry 转换为字符串呢?

    JarEntry jarEntry = connection.getJarEntry();
    JarFile archive = connection.getJarFile();
    Enumeration<JarEntry> entries = archive.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String name = jarEntry.getName();
        if (entry.getName().startsWith(name) && !entry.isDirectory()) {
                     // Convert this entry to a string
        }
    }

编辑:

我认为应该这样做:

            InputStream inputStream = archive.getInputStream(entry);
            StringWriter writer = new StringWriter();
            IOUtils.copy(inputStream, writer, "UTF-8");
            String theString = writer.toString();
            System.out.println(theString);
4

2 回答 2

0

一种可能:

private String readFileFromJar(String pathname) throws IOException {

InputStream configStream = getClass().getResourceAsStream(pathname);
try {
    FileChannel fc = stream.getChannel();
    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    /* Instead of using default, pass in a decoder. */
    return Charset.defaultCharset().decode(bb).toString();
}
finally {
    stream.close();
 }

}

然后:

if (entry.getName().startsWith(name) && !entry.isDirectory()) {
        String content = readFile(name);
}
于 2012-12-16T15:05:56.243 回答
0

找到您的条目后,请执行此操作

        BufferedReader rdr = new BufferedReader(new InputStreamReader(archive.getInputStream(jarEntry)));
        StringBuilder sb = new StringBuilder();
        for (int c = 0; (c = rdr.read()) != -1;) {
            sb.append((char) c);
        }
        String txt = sb.toString();
于 2012-12-16T15:31:37.047 回答