Java java压缩json

java压缩json文件的方法有哪些

小亿
340
2023-07-04 01:51:54
栏目: 编程语言

在Java中,可以使用以下方法压缩JSON文件:

  1. 使用GZIP压缩:可以使用Java的GZIPOutputStream类将JSON文件压缩为gzip格式。下面是一个示例代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class GzipCompressionExample {
public static void main(String[] args) {
String inputFile = "input.json";
String outputFile = "output.json.gz";
try (FileInputStream fis = new FileInputStream(inputFile);
GZIPOutputStream gzipOS = new GZIPOutputStream(new FileOutputStream(outputFile))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
gzipOS.write(buffer, 0, bytesRead);
}
System.out.println("JSON file compressed successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
  1. 使用ZIP压缩:可以使用Java的ZipOutputStream类将JSON文件压缩为zip格式。下面是一个示例代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipCompressionExample {
public static void main(String[] args) {
String inputFile = "input.json";
String outputFile = "output.zip";
try (FileInputStream fis = new FileInputStream(inputFile);
ZipOutputStream zipOS = new ZipOutputStream(new FileOutputStream(outputFile))) {
ZipEntry zipEntry = new ZipEntry(inputFile);
zipOS.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
zipOS.write(buffer, 0, bytesRead);
}
zipOS.closeEntry();
System.out.println("JSON file compressed successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

这些方法可以将JSON文件压缩为gzip或zip格式,以减小文件大小并方便传输和存储。

0
看了该问题的人还看了