gpt4 book ai didi

java - BufferedReader 中的 GZIPInputStream 文件结束序列

转载 作者:行者123 更新时间:2023-11-29 06:11:49 26 4
gpt4 key购买 nike

我使用 Java BufferedReader 对象逐行读取指向有效 GZIP 存档的 GZIPInputStream,该存档包含 1,000 行 ASCII 文本,采用典型的 CSV 格式。代码如下所示:

BufferedReader buffer = new BufferedReader(new InputStreamReader(
new GZIPInputStream(new FileInputStream(file))));

其中 file 是指向存档的实际文件对象。

我通过调用通读了所有文件

int count = 0;
String line = null;

while ((line = reader.readLine()) != null)
{
count++;
}

并且读取器按预期遍历文件,但最后它绕过第 1000 行并再读取一行(即,循环结束后计数 = 1001)。

在最后一行调用 line.length() 会报告大量 (4,000+) 个字符,所有这些字符都是不可打印的 (Character.getNumericValue() 返回 -1)。

实际上,如果我执行 line.getBytes() 结果 byte[] 数组具有相同数量的 NULL 字符 ('\0')。

这看起来像是 BufferedReader 中的错误吗?

无论如何,任何人都可以提出绕过此行为的解决方法吗?

编辑:更奇怪的行为:读取的第一行以文件名、几个 NULL 字符('\0')和行用户名和组名为前缀,然后是实际文本!

编辑:我创建了一个非常简单的测试类,它重现了我上面描述的效果,至少在我的平台上是这样。

编辑:显然是误报,我得到的文件不是纯 GZIP 而是 tar GZIP,所以这解释了它,不需要进一步测试。谢谢大家!

最佳答案

我想我发现了你的问题。

我尝试用问题中的来源重现它,并得到了这个输出:

-------------------------------------
Reading PLAIN file
-------------------------------------

Printable part of line 1: This, is, line, number, 1

Line start (<= 25 characters): This__is__line__number__1

No NULL characters in line 1

Other information on line 1:
Length: 25
Bytes: 25
First byte: 84

Printable part of line 10: This, is, line, number, 10

Line start (<= 26 characters): This__is__line__number__10

No NULL characters in line 10

Other information on line 10:
Length: 26
Bytes: 26
First byte: 84

File lines read: 10

-------------------------------------
Reading GZIP file
-------------------------------------

Printable part of line 1: This, is, line, number, 1

Line start (<= 25 characters): This__is__line__number__1

No NULL characters in line 1

Other information on line 1:
Length: 25
Bytes: 25
First byte: 84

Printable part of line 10: This, is, line, number, 10

Line start (<= 26 characters): This__is__line__number__10

No NULL characters in line 10

Other information on line 10:
Length: 26
Bytes: 26
First byte: 84

File lines read: 10

-------------------------------------
TOTAL READ
-------------------------------------

Plain: 10, GZIP: 10

我认为这不是您所拥有的。为什么?您正在使用 tar.gz 文件。这是 tar archive format ,另外还有 gzip 压缩。 GZipInputStream 撤消 gzip 压缩,但对 tar 存档格式一无所知。

tar 通常用于将多个文件打包在一起 - 以未压缩格式,但与一些元数据一起打包,这是您观察到的:

EDIT: More weird behavior: The first line read is prefixed by the filename, several NULL characters ('\0') and things line username and group name, then the actual text follows!

如果您有一个tar 文件,您需要使用一个tar 解码器。 How do I extract a tar file in Java?给出了一些链接(比如使用 Ant 的 Tar 任务),还有 JTar .

如果你只想发送一个文件,最好直接使用gzip格式(我在测试中就是这样做的)。

但是除了您希望 gzip 流读取 tar 格式之外,没有任何错误。

关于java - BufferedReader 中的 GZIPInputStream 文件结束序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6505965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com