java 将 ZipEntry 数据写入字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13311856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write ZipEntry Data To String
提问by StuStirling
I have retrieved a zip entry from a zip file like so.
我已经从这样的 zip 文件中检索了一个 zip 条目。
InputStream input = params[0];
ZipInputStream zis = new ZipInputStream(input);
ZipEntry entry;
try {
while ((entry = zis.getNextEntry())!= null) {
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This works fine and its getting my ZipEntry
no problem.
这工作正常,它让我ZipEntry
没问题。
My Question
我的问题
How can I get the contents of these ZipEntries
into a String as they are xml and csv files.
我如何将这些内容ZipEntries
转换为字符串,因为它们是 xml 和 csv 文件。
回答by Blackbelt
you have to read from the ZipInputStream
:
你必须阅读ZipInputStream
:
StringBuilder s = new StringBuilder();
byte[] buffer = new byte[1024];
int read = 0;
ZipEntry entry;
while ((entry = zis.getNextEntry())!= null) {
while ((read = zis.read(buffer, 0, 1024)) >= 0) {
s.append(new String(buffer, 0, read));
}
}
When you exit from the inner while
save the StringBuilder
content, and reset it.
当您从内部退出时while
保存StringBuilder
内容,并重置它。
回答by Igor Bljahhin
Here is the approach, which does not break Unicode characters:
这是不破坏 Unicode 字符的方法:
final ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(content));
final InputStreamReader isr = new InputStreamReader(zis);
final StringBuilder sb = new StringBuilder();
final char[] buffer = new char[1024];
while (isr.read(buffer, 0, buffer.length) != -1) {
sb.append(new String(buffer));
}
System.out.println(sb.toString());
回答by Andrii Nemchenko
With set encoding (UTF-8) and without creation of strings:
使用设置编码 (UTF-8) 并且不创建字符串:
import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;
import java.io.ByteArrayOutputStream;
import static java.nio.charset.StandardCharsets.UTF_8;
String charset = "UTF-8";
try (
ZipInputStream zis = new ZipInputStream(input, UTF_8);
ByteArrayOutputStream baos = new ByteArrayOutputStream()
) {
byte[] buffer = new byte[1024];
int read = 0;
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null)
while ((read = zis.read(buffer, 0, buffer.length)) > 0)
baos.write(buffer, 0, read);
String content = baos.toString(charset);
}
回答by Kreender
I would use apache's IOUtils
我会使用 apache 的 IOUtils
ZipEntry entry;
InputStream input = params[0];
ZipInputStream zis = new ZipInputStream(input);
try {
while ((entry = zis.getNextEntry())!= null) {
String entryAsString = IOUtils.toString(zis, StandardCharsets.UTF_8);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
IOUtils.closeQuietly(zis);