Selama proses transfer file, untuk membuat file besar lebih nyaman dan transmisi cepat, kompresi umumnya digunakan untuk mengompres file sebelum ditransfer. Kelas deflater dan inflater dalam paket java.util.zip di Java memberi pengguna fungsi kompresi dari algoritma lempeng. Berikut ini adalah implementasi kompresi dan dekompresi yang ditulis dengan sendirinya, dan konten file kompresi diilustrasikan sebagai contoh. Metode spesifik yang terlibat dapat dilihat di JDK API untuk informasi.
/ ** * * @param inputByte * array byte untuk didekompresi * @return array byte decompressed * @throws ioException */ public static byte [] uncompress (byte [] inputByte) melempar ioException {int len = 0; Inflater infl = inflater baru (); infl.setInput (inputByte); BytearrayoutputStream bos = new bytearrayoutputStream (); byte [] outbyte = byte baru [1024]; coba {while (! infl.finished ()) {// mendekompresi dan output konten dekompresi ke aliran output byte bos len = infl.inflate (outbyte); if (len == 0) {break; } bos.write (outbyte, 0, len); } infl.end (); } catch (Exception e) {//} akhirnya {bos.close (); } return bos.tobyteArray (); } /*** kompres. * * @param inputByte * array byte untuk dikompresi * @return data terkompresi * @throws ioException */ public static byte [] compress (byte [] inputByte) melempar ioException {int len = 0; Deflater defl = deflater baru (); defl.setInput (inputByte); defl.finish (); BytearrayoutputStream bos = new bytearrayoutputStream (); byte [] outputByte = byte baru [1024]; coba {while (! Defl.finished ()) {// kompres dan output konten terkompresi ke aliran output byte bos len = defl.deflate (outputByte); bos.write (outputbyte, 0, len); } defl.end (); } akhirnya {bos.close (); } return bos.tobyteArray (); } public static void main (string [] args) {coba {fileInputStream fis = new fileInputStream ("d: //testdeflate.txt"); int len = fis.available (); byte [] b = byte baru [len]; fis.read (b); byte [] bd = kompres (b); // Agar konten terkompresi ditransmisikan pada jaringan, string encoding base64 umumnya digunakan untuk digunakan untuk mengkode encodestr = base64.encodeBase64String (BD); byte [] bi = uncompress (base64.decodebase64 (encodeStr)); FileOutputStream fos = new fileoutputStream ("d: //testinflate.txt"); fos.write (bi); fos.flush (); fos.close (); fis.close (); } catch (Exception e) {//}}Metode Implementasi Kompresi Pengelupasan di atas di Java adalah semua konten yang telah saya bagikan dengan Anda. Saya harap Anda dapat memberi Anda referensi dan saya harap Anda dapat mendukung wulin.com lebih lanjut.