(Original) Android reads the content of a file in the compressed package

In development, sometimes it is necessary to read the file, but what if the file is in the compressed package?

In fact, Android also provides corresponding processing methods

I will introduce it today

The main one used is the ZipFile class

The specific code is as follows

 ZipFile zip = new ZipFile(zipFilepath);

zipFilepath is the path of the compressed package you want to read

Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();

Here to return an enumeration class through enumeration

Next is the core code

        StringBuilder content = new StringBuilder();
        ZipEntry ze;
        // 枚举zip文件内的文件/
        while (entries.hasMoreElements()) {
            ze = entries.nextElement();
            // 读取目标对象
            if (ze.getName().equals(readFileName)) {
                Scanner scanner = new Scanner(zip.getInputStream(ze));
                while (scanner.hasNextLine()) {
                    content.append(scanner.nextLine());
                }
                scanner.close();
            }
        }
        zip.close();

By traversing this enumeration class

Find the files in this compressed package according to the file name

Then start to read the contents of this file

Write to content

This can be used to read the text content of a basic txt file

You can also modify it yourself according to business needs

The second method is described below

ZipFile zip=new ZipFile(new File(fileName));

Create this class as before

        ZipEntry zipEntry=zip.getEntry("test.txt");//通过getEntry(name)得到指定的文件类
        if(zipEntry!=null){
            Log.d("print", "已经查找到该文件");
        }else {
            Log.d("print", "该文件不存在");
        }

This method is simpler than the traversal method just now

After confirming the name of the file to be found in the compressed package

You can directly use this method to obtain the file

Then the way to read the file is the same as in method one

Guess you like

Origin blog.csdn.net/Android_xiong_st/article/details/100142227
Recommended