![](/img/trans.png)
[英]Question about reading from a ZipInputStream/ZipEntry in java
[英]Java ZipInputStream not reading entire ZipEntry
我正在尝试从ZIP存档中读取XML文件。 相关代码如下:
ZipInputStream zis = new ZipInputStream(is);
ZipEntry entry = zis.getNextEntry();
while(entry != null) {
if(entry.getName().equals("plugin.xml")) {
int size = (int)entry.getSize();
byte[] bytes = new byte[size];
int read = zis.read(bytes, 0, size);
System.out.println("File size: " + size);
System.out.println("Bytes read: " + read);
}
}
这在工作时产生如下输出:
File size: 5224
Bytes read: 5224
正在读取的plugin.xml
文件没有什么特别的,并且可以通过我能找到的任何XML验证,但是,对XML文件进行的细微更改(删除字符,添加字符等) 有时会导致从文件中读取“字节”的情况。输入流小于文件大小。 在这种情况下,我更改了与上述相同文件的XML属性的文本值,并得到以下结果:
File size: 5218
Bytes read: 5205 // the reader stopped early!
我看不到任何模式可以使用哪些XML文件,哪些不能使用。 这似乎是完全随机的。
有人遇到过这样的事情吗?
编辑:忘了提及,在plugin.xml
文件中读取的Java代码嵌入在我无法更改的现成应用程序中。 我的问题是试图了解为什么在某些情况下它不接受我的XML文件。
它在哪里说InputStream.read()
或其任何实现或重写填充缓冲区? 检查Javadoc。 实际上,是说read()
返回-1表示EOS或将至少一个字节读入缓冲区。 你必须循环。
如前所述,您需要使用循环。 我必须解决这个确切的问题,所以我想举个例子。
ZipInputStream zis = new ZipInputStream(is);
ZipEntry entry = zis.getNextEntry();
while(entry != null) {
if(entry.getName().equals("plugin.xml")) {
int size = (int)entry.getSize();
byte[] bytes = new byte[size];
int read = 0;
while (read < size) {
read += zis.read(bytes, read, (size - read));
}
System.out.println("File size: " + size);
System.out.println("Bytes read: " + read);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.