Home Java javaTutorial Detailed explanation of how to read and write files in the assets directory in Android

Detailed explanation of how to read and write files in the assets directory in Android

Jan 17, 2017 pm 03:10 PM

Android resource files can be roughly divided into two types:

The first is the compilable resource file stored in the res directory:

This resource file system will be in R.java The ID of the resource file is automatically generated, so accessing this resource file is relatively simple, just pass R.XXX.ID;

The second is the native resource file stored in the assets directory:

Because the system does not compile the resource files under assets during compilation, we cannot access them through R.XXX.ID. So can we access them through the absolute path of the resource? Because after the apk is installed, it will be placed in the /data/app/**.apk directory and exist in the form of apk. Asset/res and are bound in the apk and will not be decompressed to the /data/data/YourApp directory, so We can't get the absolute paths to assets directly because they don't exist.

Fortunately, the Android system provides us with an AssetManager tool class.

Looking at the official API, we can see that AssetManager provides access to the original resource files of the application; this class provides a low-level API that allows you to open and read and apply in the form of a simple byte stream. The raw resource files that the program bundles together.

In addition to providing the /res directory to store resource files, Android also provides storage of resource files in the /assets directory. IDs will not be automatically generated in R.java under the /assets directory, so read the assets directory. The resource files need to provide paths, and we can access these files through the AssetManager class.
The author needs to copy resources from A.apk (resource apk, put all resources such as: so, apk, executable files, etc. under the assets directory, apk does not implement logical code) to the specified directory, so the author creates A B.apk (a Service, which can also be implemented with Activity) is created to implement resource copy logic. Since the copy path is generally inaccessible or created (each apk can only access /data/data/own package name/ after installation) Private space below), if the author needs this apk to obtain system permissions (System permissions), the shareduserid must be declared in AndroidManifest.xml. The specific operation will be recorded in the next section.


1. Several commonly used APIs for AssetManager to read files

1. File reading method
AssetManager.open(String filename) returns an InputSteam type Byte stream, the filename here must be a file, not a folder. The open method of AssetManager to open resource files is an overloaded method. You can add an int parameter of the opening method, and corresponding operations can be performed according to different parameters. For details, please see the official document http://web.mit.edu/clio/MacData/afs/sipb/project/android/docs/reference/android/content/res/AssetManager.html
2. Resource files can exist Folders and subdirectories
public final String[]list(String path), returns the names of all files and subdirectories under the current directory. Access to all resource files can be achieved by recursively traversing the entire file directory. String[] Array of strings, one for each asset. These file names are relative to 'path'. You can open the file by concatenating 'path' and a name in the returned string (via File) and passing that to open() .

2. Related implementation code
Resource APK (A.apk)

Detailed explanation of how to read and write files in the assets directory in Android

Specific implementation code snippet, due to the use of system permissions, the generated path You can change B.apk yourself

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {
      ctxDealFile = this.createPackageContext("com.zlc.ipanel",
          Context.CONTEXT_IGNORE_SECURITY);
    } catch (NameNotFoundException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    
    btn3.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        try {
          String uiFileName = "ipanelJoin";
          deepFile(ctxDealFile, uiFileName);
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          textView.setText("file is wrong");
        }
      }
    });
    //
  }
  public void deepFile(Context ctxDealFile, String path) {
    try {
      String str[] = ctxDealFile.getAssets().list(path);
      if (str.length > 0) {//如果是目录
        File file = new File("/data/" + path);
        file.mkdirs();
        for (String string : str) {
          path = path + "/" + string;
          System.out.println("zhoulc:\t" + path);
          // textView.setText(textView.getText()+"\t"+path+"\t");
          deepFile(ctxDealFile, path);
          path = path.substring(0, path.lastIndexOf('/'));
        }
      } else {//如果是文件
        InputStream is = ctxDealFile.getAssets().open(path);
        FileOutputStream fos = new FileOutputStream(new File("/data/"
            + path));
        byte[] buffer = new byte[1024];
        int count = 0;
        while (true) {
          count++;
          int len = is.read(buffer);
          if (len == -1) {
            break;
          }
          fos.write(buffer, 0, len);
        }
        is.close();
        fos.close();
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Copy after login

For more detailed information on how to read and write files in the assets directory in Android, please pay attention to the PHP Chinese website for related articles!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

See all articles