在Java中,可以使用Deflater
類來實現XML字符串的壓縮。以下是一個簡單的示例:
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class XmlCompression {
public static void main(String[] args) throws IOException {
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><element>Content</element></root>";
byte[] compressedBytes = compressXml(xmlString);
System.out.println("Compressed XML: " + new String(compressedBytes, StandardCharsets.UTF_8));
}
public static byte[] compressXml(String xmlString) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
deflaterOutputStream.write(xmlString.getBytes(StandardCharsets.UTF_8));
deflaterOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
}
在這個示例中,我們首先創建了一個包含XML字符串的ByteArrayOutputStream
對象。然后,我們創建了一個Deflater
對象,并設置了壓縮級別為Deflater.BEST_COMPRESSION
。接下來,我們創建了一個DeflaterOutputStream
對象,將ByteArrayOutputStream
和Deflater
對象作為參數傳遞。最后,我們將XML字符串寫入DeflaterOutputStream
,并關閉流。這將返回一個壓縮后的字節數組。