2012-12-16 20 views
0

我迭代了一些我知道是文本文件的JarEntries。但是当我找到它时,如何将JarEntry转换为字符串?将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); 
+0

名已经是字符串,或DOY你想要的文本文件的内容TPO被作为字符串读? – AlexWien

+0

是它的必须转换成字符串的条目的内容 – u123

回答

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); 
} 
+0

由于资源在jar文件中,文件将不起作用。 – u123

+0

更新代码以使用resourceAsStream – AlexWien

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();