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

高洛峰
Release: 2017-01-17 15:10:49
Original
2068 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template