我正在使用jpountz LZ4来尝试压缩文件,并且我想使用Java文件输入和输出流来读取和输出文件。我试图在网上找到解决方案,但是没有找到。我在之前的stackoverflow问题中发现了如何正确实现LZ4的问题,并尝试修改它以使用流,但我不确定这是否正确或者是否有效。
当压缩文本文件时,输出的文件会缺少某些字符或替换为符号。
但是当使用图像文件运行时,它会抛出一个越界错误。我还无法使解压缩工作,因为它抛出一个“解码输入缓冲区偏移3的错误”。以下是我的代码,任何帮助将不胜感激,谢谢。
当压缩文本文件时,输出的文件会缺少某些字符或替换为符号。
ðHello world Heðo world Hello ðrld Hello worlðHello worl
但是当使用图像文件运行时,它会抛出一个越界错误。我还无法使解压缩工作,因为它抛出一个“解码输入缓冲区偏移3的错误”。以下是我的代码,任何帮助将不胜感激,谢谢。
public void LZ4Compress(InputStream in, OutputStream out){
int noBytesRead = 0; //number of bytes read from input
int noBytesProcessed = 0; //number of bytes processed
try {
while ((noBytesRead = in.read(inputBuffer)) >= 0) {
noBytesProcessed = inputBuffer.length;
decompressedLength = inputBuffer.length;
outputBuffer = compress(inputBuffer, decompressedLength);
out.write(outputBuffer, 0, noBytesRead);
}
out.flush();
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void LZ4decompress(InputStream in, OutputStream out){
int noBytesRead = 0; //number of bytes read from input
try {
while((noBytesRead = in.read(inputBuffer)) >= 0){
noBytesProcessed = inputBuffer.length;
outputBuffer = decompress(inputBuffer);
out.write(outputBuffer, 0, noBytesRead);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] compress(byte[] src, int srcLen) {
decompressedLength = srcLen;
int maxCompressedLength = compressor.maxCompressedLength(decompressedLength);
byte[] compressed = new byte[maxCompressedLength];
int compressLen = compressor.compress(src, 0, decompressedLength, compressed, 0, maxCompressedLength);
byte[] finalCompressedArray = Arrays.copyOf(compressed, compressLen);
return finalCompressedArray;
}
private static LZ4SafeDecompressor decompressor = factory.safeDecompressor();
public static byte[] decompress(byte[] finalCompressedArray) {
byte[] restored = new byte[finalCompressedArray.length];
restored = decompressor.decompress(finalCompressedArray, finalCompressedArray.length);
return restored;
}
noBytesProcessed = inputBuffer.length
: 这里出了问题。应该是noBytesProcessed = noBytesRead
,类似地,decompressedLength
以及其他所有你假设read()
填充缓冲区的地方也是如此。 - user207421