java语言编写LZ算法
时间: 2023-11-28 14:45:43 浏览: 152
以下是Java语言编写LZ算法的示例代码:
```java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class LZ77 {
public static byte[] compress(byte[] data) throws IOException {
Deflater deflater = new Deflater();
deflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
deflater.finish();
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
byte[] compressedData = outputStream.toByteArray();
return compressedData;
}
public static byte[] decompress(byte[] compressedData) throws IOException {
Inflater inflater = new Inflater();
inflater.setInput(compressedData);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(compressedData.length);
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
try {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
} catch (Exception e) {
e.printStackTrace();
}
}
outputStream.close();
byte[] decompressedData = outputStream.toByteArray();
return decompressedData;
}
}
```
该示例代码使用Java内置的Deflater和Inflater类实现了LZ77算法的压缩和解压缩功能。其中,compress方法接收一个字节数组作为输入,返回一个压缩后的字节数组;decompress方法接收一个压缩后的字节数组作为输入,返回一个解压缩后的字节数组。
阅读全文