久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

java壓縮字符串的方法是什么

158次閱讀
沒有評論

共計 1454 個字符,預計需要花費 4 分鐘才能閱讀完成。

在 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 方法用于解壓縮輸入的字節數組。通過這兩個方法,可以實現字符串的壓縮和解壓縮操作。

丸趣 TV 網 – 提供最優質的資源集合!

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2024-04-07發表,共計1454字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 阿拉善右旗| 阳春市| 大埔区| 滦南县| 洪湖市| 当阳市| 兴宁市| 七台河市| 绵阳市| 乌兰县| 华阴市| 常德市| 台南市| 南乐县| 临泽县| 炉霍县| 轮台县| 电白县| 玉门市| 依兰县| 仙游县| 绥阳县| 丹寨县| 广宁县| 新郑市| 高碑店市| 平陆县| 藁城市| 宣汉县| 西乌| 鄯善县| 昌邑市| 贺州市| 苏尼特右旗| 九寨沟县| 巴青县| 平利县| 闵行区| 泰来县| 盐源县| 栾城县|