Writing in the front

Learn how to compress data (String->byte[]), compress and decompress files in Android by reading this article. It takes about five to ten minutes to read this article. I am a rookie and hope to communicate more.

Compress the data

  1. Download the latest SDK file from the 7z website. Portal: www.7-zip.org/sdk.html.

  1. CV the code we need into our project. Path: Java/servenZip

  1. After copying the code into our project, write your own method of compression.


public byte[] lzmaZip(String xml) throws IOException{   
  BufferedInputStream inStream = new BufferedInputStream(new ByteArrayInputStream(xml.getBytes()));   
  ByteArrayOutputStream bos = new ByteArrayOutputStream();   
     
  boolean eos = true;   
    Encoder encoder = new Encoder();   
    encoder.SetEndMarkerMode(eos);   
    encoder.WriteCoderProperties(bos);   
    long fileSize = xml.length();   
    if (eos)   
      fileSize = -1;   
    for (int i = 0; i < 8; i++)   
      bos.write((int)(fileSize >>> (8 * i)) & 0xFF);   
    encoder.Code(inStream, bos, -1, -1.null);   
    return bos.toByteArray() ;   
}   
Copy the code

* : Encoder is Compression/LZMA/Encoder.

  1. We must be skeptical of the byte [] we get. The next thing we need to do is verify our approach with the big God project. Github:github.com/hzy3774/And… (not myself), the god through C code, to achieve 7Z decompression. And the author is very responsible very enthusiastic, I help him to hit an advertisement here…. Manual Smiley face app ☻. Project C uses header files with NDK versions below bit 14, so I started compiling with NDK16 with missing header files. On December 4, 2017, at 16:28:46).

  2. The byte [] obtained by us is saved locally as a file, and the suffix is 7z.


try {
            byte[] ss = SevenZipUtil.lzmaZip("Good luck, chicken tonight!");
            createFileWithByte(ss);
            appUtils.logError("7Z after compression:"+ Arrays.toString(ss));
        } catch (IOException e) {
            e.printStackTrace();
        }
Copy the code

Byte [] Save to a file


/** * Generate files from byte arrays **@paramBytes * Array of bytes used to generate the file */
    private void createFileWithByte(byte[] bytes) {
        // TODO Auto-generated method stub
        /** * Create the File object, which contains the directory where the File is located and the name of the File */
        File file = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + File.separator + "ds"."two.7z");
        // Create a FileOutputStream object
        FileOutputStream outputStream = null;
        // Create a BufferedOutputStream object
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // Delete the file if it exists
            if (file.exists()) {
                file.delete();
            }
            // Create a new empty file in the file system based on the path
            file.createNewFile();
            // Get the FileOutputStream object
            outputStream = new FileOutputStream(file);
            // Get the BufferedOutputStream object
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            // Write byte data to the buffered output stream where the file resides
            bufferedOutputStream.write(bytes);
            // Spawn the buffered output stream. This step is critical. If you do not execute flush(), the contents of the file will be empty.
            bufferedOutputStream.flush();
        } catch (Exception e) {
            // Prints the exception information
            e.printStackTrace();
        } finally {
            // Close the created stream object
            if(outputStream ! =null) {
                try {
                    outputStream.close();
                } catch(IOException e) { e.printStackTrace(); }}if(bufferedOutputStream ! =null) {
                try {
                    bufferedOutputStream.close();
                } catch(Exception e2) { e2.printStackTrace(); }}}}Copy the code

After saving the phone successfully, we use the ApK of the great God to find the location of the folder and decompress it. Then we enter the file management interface, looking for the decompressed file, view the file content, after verification, this method is feasible. So make a note here. Also to fill in their own blog less situation. (It’s too good…)

Finally, add the tool class SevenZipUtil that I use:


/** * unzip 7z file * Created by pul on 2017/12/1. */

public class SevenZipUtil {
    private final String TAG = "SevenZipUtil";

    /** * Compress the string into an array of bytes **@param xml
     * @return
     * @throws IOException
     */
    public static byte[] lzmaZip(String xml) throws IOException {
        BufferedInputStream inStream = new BufferedInputStream(new ByteArrayInputStream(xml.getBytes()));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        boolean eos = true;
        Encoder encoder = new Encoder();
        encoder.SetEndMarkerMode(eos);
        encoder.WriteCoderProperties(bos);
        long fileSize = xml.length();
        if (eos)
            fileSize = -1;
        for (int i = 0; i < 8; i++)
            bos.write((int) (fileSize >>> (8 * i)) & 0xFF);
        encoder.Code(inStream, bos, -1, -1.null);
        return bos.toByteArray();
    }

    /** * Decompress the 7z file */
    public void extractile(String filepath) {
        RandomAccessFile randomAccessFile = null;
        IInArchive inArchive = null;

        try {
            randomAccessFile = new RandomAccessFile(filepath, "r");
            inArchive = SevenZip.openInArchive(null.new RandomAccessFileInStream(randomAccessFile));

            // Getting simple interface of the archive inArchive
            ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();

            Log.e(TAG," Hash | Size | Filename");
            Log.e(TAG,"-- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- --");

            for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
                final int[] hash = new int[] {0};
                if(! item.isFolder()) { ExtractOperationResult result;final long[] sizeArray = new long[1];
                    result = item.extractSlow(new ISequentialOutStream() {
                        public int write(byte[] data) throws SevenZipException {

                            //Write to file
                            FileOutputStream fos;
                            try {
                                File file = new File(item.getPath());
                                //error occours below
// file.getParentFile().mkdirs();
                                fos = new FileOutputStream(file);
                                fos.write(data);
                                fos.close();

                            } catch (FileNotFoundException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                            hash[0] ^= Arrays.hashCode(data); // Consume data
                            sizeArray[0] += data.length;
                            return data.length; // Return amount of consumed data}});if (result == ExtractOperationResult.OK) {
                        Log.e(TAG,String.format("%9X | %10s | %s".//
                                hash[0], sizeArray[0], item.getPath()));
                    } else {
                        Log.e(TAG,"Error extracting item: "+ result); }}}}catch (Exception e) {
            Log.e(TAG,"Error occurs: " + e);
            e.printStackTrace();
            System.exit(1);
        } finally {
            if(inArchive ! =null) {
                try {
                    inArchive.close();
                } catch (SevenZipException e) {
                    System.err.println("Error closing archive: "+ e); }}if(randomAccessFile ! =null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                }
            }
        }
    }
}
Copy the code