在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格式,以減小文件大小并方便傳輸和存儲。