java压缩字符串的方法是什么

   2024-10-26 9600
核心提示:在Java中,可以使用java.util.zip包中的Deflater和Inflater类来进行字符串的压缩和解压缩操作。以下是一个简单的示例代码:impor

在Java中,可以使用java.util.zip包中的DeflaterInflater类来进行字符串的压缩和解压缩操作。以下是一个简单的示例代码:

import java.util.zip.Deflater;import java.util.zip.Inflater;public class Main {    public static byte[] compressString(String input) {        try {            byte[] inputBytes = input.getBytes();            Deflater deflater = new Deflater();            deflater.setInput(inputBytes);            deflater.finish();            byte[] outputBytes = new byte[inputBytes.length];            int compressedSize = deflater.deflate(outputBytes);            byte[] compressedBytes = new byte[compressedSize];            System.arraycopy(outputBytes, 0, compressedBytes, 0, compressedSize);            return compressedBytes;        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    public static String decompressString(byte[] input) {        try {            Inflater inflater = new Inflater();            inflater.setInput(input);            byte[] outputBytes = new byte[input.length];            int decompressedSize = inflater.inflate(outputBytes);            byte[] decompressedBytes = new byte[decompressedSize];            System.arraycopy(outputBytes, 0, decompressedBytes, 0, decompressedSize);            return new String(decompressedBytes);        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    public static void main(String[] args) {        String input = "Hello, this is a test string for compression.";        byte[] compressedData = compressString(input);        String decompressedData = decompressString(compressedData);        System.out.println("Original data: " + input);        System.out.println("Compressed data: " + new String(compressedData));        System.out.println("Decompressed data: " + decompressedData);    }}

在上面的示例中,compressString方法用于压缩输入的字符串,而decompressString方法用于解压缩输入的字节数组。通过这两个方法,可以实现字符串的压缩和解压缩操作。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号