在Java中,可以使用以下方法压缩JSON文件:
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();
}
}
}
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格式,以减小文件大小并方便传输和存储。