android's manipulation of files under asset and raw

Keywords: Android Java MediaPlayer

android's manipulation of files under asset and raw

There are two kinds of resources in Android, one is compilable resource file under res. This resource file system automatically generates the ID of the resource file in R.Java, and the access is very simple. It only needs to call R.XXX.id. The second is the native resource file under the assets folder. The file under this folder will not be compiled by R file, so it can't be like the first one. Android provides a tool class for us to access the files under the assets file: AssetManager.

Introduction function
String[] list(String path);//List the names of subordinate files and folders under this directory
InputStream open(String fileName);//Open the file in sequential read mode, default mode is ACCESS_STREAMING
 
 InputStream open(String fileName, int accessMode);//Open the file in the specified mode. There are several reading modes:
                                    //ACCESS_UNKNOWN: No specific read mode is specified
                                    //ACCESS_RANDOM: Random Reading
                                    //ACCESS_STREAMING: Sequential Reading
                                    //ACCESS_BUFFER: Cache Read
void close()//Close the AssetManager instance
Load Web pages under assets directory
webView.loadUrl("file:///android_asset/html/index.htmll");

Description: This way can load the web pages under the assets directory, and the css, js, pictures and other files related to the web pages will also be loaded.

Load image resources in assets directory
InputStream is = getAssets().open(fileName);  
bitmap = BitmapFactory.decodeStream(is); 
ivImg.setImageBitmap(bitmap);
Load the file below the assets directory
InputStream is = getAssets().open(fileName);  
int lenght = is.available();  
byte[]  buffer = new byte[lenght];  
is.read(buffer);  
String result = = new String(buffer, "utf8");
Load music in assets directory
// Open the specified music file to get the AssetFileDescriptor object of the specified file in the assets directory  
AssetFileDescriptor afd = am.openFd(music);  
mPlayer.reset();  
// Use MediaPlayer to load the specified sound file.  
mPlayer.setDataSource(afd.getFileDescriptor(),  
    afd.getStartOffset(), afd.getLength());  
// Prepare for voice  
mPlayer.prepare();  
// play  
mPlayer.start();  
Loading videos in assets directory
private void initview() {
         vv = (CustomVideoView) view.findViewById(R.id.videoView111);
         //vv.setVideoPath("/mnt/hd/Wonder Girls - Nobody.avi");
         Uri uri = copyFile("one.3gp");
         vv.setVideoURI(uri); 
         vv.start();
     }
     
  public Uri copyFile(String name) {
         try {
             File dir = getActivity().getFilesDir();
             File file = new File(dir, name);
             if (file.exists()) {
                 Log.d("Test", "=========file exist=========");
                 return Uri.fromFile(file);
             } else {
                 file.createNewFile();
                 OutputStream os = new FileOutputStream(file);
                 InputStream is = getActivity().getAssets().open(name);
                 byte[] buffer = new byte[1024];
                 int bufferRead = 0;
                 while((bufferRead = is.read(buffer)) != -1) {
                     os.write(buffer, 0, bufferRead);
                 }
                 os.flush();
                 is.close();
                 os.close();
                 Log.d("Test", "=========copyFile success=========");
                 return Uri.fromFile(file);
             }
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         return null;
     }
Get the resource return flow and file path in the raw directory
/**
 * Get the resources in the raw directory
 *
 * @param resId Resource id
 */
public static InputStream getRawStream(Context context, int resId) {
    return context.getResources().openRawResource(resId);

}
/**
 * Get the resources in the raw directory
 *
 * @param resId Resource id
 */
public static String getRawFilePath(Context context, int resId) {
    return "android.resource://" + context.getPackageName() + "/" + resId;
}

Copy the files in assets to the specified path
/**  

Copy the entire folder content from the assets directory  

@param  context  Context Activity using the CopyFiles class 

@param  oldPath  String  The original file path is as follows: / aa  

@param  newPath  String  Copied paths such as: xx:/bb/cc  
*/   
public void copyFilesFassets(Context context,String oldPath,String newPath) {                      
    try {  
   String fileNames[] = context.getAssets().list(oldPath);//Get all the files and directory names in the assets directory  
   if (fileNames.length > 0) {//If it is a directory  
       File file = new File(newPath);  
       file.mkdirs();//If the folder does not exist, then recursion  
       for (String fileName : fileNames) {  
          copyFilesFassets(context,oldPath + "/" + fileName,newPath+"/"+fileName);  
       }  
   } else {//If it is a document  
       InputStream is = context.getAssets().open(oldPath);  
       FileOutputStream fos = new FileOutputStream(new File(newPath));  
       byte[] buffer = new byte[1024];  
       int byteCount=0;                 
       while((byteCount=is.read(buffer))!=-1) {//Loop reads buffer bytes from the input stream          
           fos.write(buffer, 0, byteCount);//Write the read input stream to the output stream  
       }  
       fos.flush();//refresh buffer  
       is.close();  
       fos.close();  
   }  
} catch (Exception e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
    //Notify UI threads if errors are caught  
               MainActivity.handler.sendEmptyMessage(COPY_FALSE);  
}                             
} 

The following is a complete tool class code directly copied to the project can be used

package com.insworks.lib_datas.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ProjectName: AndroidTemplateProject2
 * @Package: com.insworks.lib_datas.utils
 * @ClassName: AssetsUtil
 * @Author: Song Jian
 * @CreateDate: 2019/8/8 14:33
 * @UpdateUser: Reneer
 * @UpdateDate: 2019/8/8 14:33
 * @UpdateRemark: Update instructions
 * @Version: 1.0
 * @Description: Assets And raw file reader class
 * <p>
 * String[] list(String path);//List the names of subordinate files and folders under this directory
 * <p>
 * InputStream open(String fileName);//Open the file in sequential read mode, default mode is ACCESS_STREAMING
 * <p>
 * InputStream open(String fileName, int accessMode);//Open the file in the specified mode. There are several reading modes:
 * //ACCESS_UNKNOWN : No specific read mode is specified
 * //ACCESS_RANDOM : Random read
 * //ACCESS_STREAMING : Sequential read
 * //ACCESS_BUFFER : Cache read
 */
public class AssetsUtil {
    /**
     * Get the Web pages in the assets directory
     * This way can load the web pages under the assets directory, and the css, js, pictures and other files related to the web pages will also be loaded.
     * webView.loadUrl("file:///android_asset/html/index.html");
     *
     * @param filePath
     */
    public static String getHtml(String filePath) {
        return "file:///android_asset/" + filePath;
    }

    /**
     * Get all the files
     *
     * @param path Catalog
     * @return
     */
    public static String[] getfiles(Context context, String path) {
        AssetManager assetManager = context.getAssets();
        String[] files = null;
        try {
            files = assetManager.list(path);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            assetManager.close();
        }
        return files;

    }

    /**
     * Get the image resources in the assets directory
     *
     * @param fileName
     */
    public static Bitmap getPic(Context context, String fileName) {
        InputStream is = null;
        Bitmap bitmap = null;
        try {
            is = context.getAssets().open(fileName);
            bitmap = BitmapFactory.decodeStream(is);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(is);
        }
        return bitmap;
    }

    /**
     * Closed flow
     *
     * @param is
     */
    private static void close(Closeable... is) {
        for (Closeable i : is) {
            try {
                i.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * Get the text resources under the assets directory
     *
     * @param fileName
     */
    public static String getTex(Context context, String fileName) {
        InputStream is = null;
        String result = "";
        try {
            is = context.getAssets().open(fileName);
            int lenght = is.available();
            byte[] buffer = new byte[lenght];
            is.read(buffer);
            result = new String(buffer, "utf8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(is);
        }
        return result;

    }

    /**
     * Get audio resources in assets directory
     *
     * @param fileName
     */
    public static AssetFileDescriptor getAudio(Context context, String fileName) {
        AssetFileDescriptor afd = null;
        try {
            // Open the specified music file to get the AssetFileDescriptor object of the specified file in the assets directory
            afd = context.getAssets().openFd(fileName);
//            MediaPlayer mPlayer=new MediaPlayer();
//            mPlayer.reset();
//        // Use MediaPlayer to load the specified sound file.
//            mPlayer.setDataSource(afd.getFileDescriptor(),
//                    afd.getStartOffset(), afd.getLength());
//            // Prepare the sound
//            mPlayer.prepare();
//        / / play
//            mPlayer.start();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(afd);
        }
        return afd;

    }

    /**
     * Get the URI in the assets directory
     * Can be used to play video resources
     *
     * @param fileName
     */
    public static Uri getUri(Context context, String fileName) {
        File file = getFile(context, fileName);
        //Play video
//        VideoView mVideoView = new VideoView(context);
//        mVideoView.setVideoURI(Uri.fromFile(file));
//        mVideoView.start();
        return Uri.fromFile(file);
    }

    /**
     * Copy the stream locally and return the default copy of the local file to the Files directory
     *
     * @param context
     * @param name
     * @return
     */
    public static File getFile(Context context, String name) {
        InputStream is = null;
        FileOutputStream os = null;
        try {
            File dir = context.getFilesDir();
            File file = new File(dir, name);
            if (file.exists()) {
                return file;

            } else {
                file.createNewFile();
                os = new FileOutputStream(file);
                is = context.getAssets().open(name);
                byte[] buffer = new byte[1024];
                int bufferRead = 0;
                while ((bufferRead = is.read(buffer)) != -1) {
                    os.write(buffer, 0, bufferRead);
                }
                os.flush();
                is.close();
                os.close();
                Log.d("Test", "=========getFile success=========");
                return file;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(is, os);
        }
        return null;
    }

    /**
     * Get the resources in the raw directory
     *
     * @param resId Resource id
     */
    public static InputStream getRawStream(Context context, int resId) {
        return context.getResources().openRawResource(resId);

    }

    /**
     * Get the resources in the raw directory
     *
     * @param resId Resource id
     */
    public static String getRawFilePath(Context context, int resId) {
        return "android.resource://" + context.getPackageName() + "/" + resId;
    }


    /**
     * Copy content from assets directory to sd card
     *
     * @param context   Context Activity using the CopyFiles class
     * @param assetPath String  The original file path is as follows: / aa
     * @param newPath   String  Copied paths such as: xx:/bb/cc
     */
    public static void copyFilesFassets(Context context, String assetPath, String newPath) {
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            String fileNames[] = context.getAssets().list(assetPath);//Get all the files and directory names in the assets directory
            if (fileNames.length > 0) {//If it is a directory
                File file = new File(newPath);
                file.mkdirs();//If the folder does not exist, then recursion
                for (String fileName : fileNames) {
                    copyFilesFassets(context, assetPath + "/" + fileName, newPath + "/" + fileName);
                }
            } else {//If it is a document
                is = context.getAssets().open(assetPath);
                fos = new FileOutputStream(new File(newPath));
                byte[] buffer = new byte[1024];
                int byteCount = 0;
                while ((byteCount = is.read(buffer)) != -1) {//Loop reads buffer bytes from the input stream
                    fos.write(buffer, 0, byteCount);//Write the read input stream to the output stream
                }
                fos.flush();//refresh buffer
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            //Notify UI threads if errors are caught
        } finally {
            close(is, fos);
        }
    }

}

About me

Private blog

Technical WeChat public number: infree6 or direct scan code

Posted by gmcalp on Mon, 07 Oct 2019 18:32:31 -0700