Android reads files in the asserts and raw folders.
It is often necessary to read files in the "/res/raw" and "/asserts" folders, and simply write them as a tool class for later use.
1. File Operation tool class in raw Folder:
/*** File processing tool class in the raw folder ***/public class RawFileUtils {private RawFileUtils () {}/*** read files in the raw folder * @ param resourceId raw file resource ID * @ return file content ***/public static String readFileFromRaw (Context context, int resourceId) {if (null = context | resourceId <0) {return null;} String result = null; try {InputStream inputStream = context. getResources (). openRawResource (resourceId); // get the number of bytes of the object int length = inputStream. available (); // create byte array byte [] buffer = new byte [length]; // read the data in the file to inputStream In the byte array. read (buffer); result = EncodingUtils. getString (buffer, "UTF-8");} catch (Exception e) {e. printStackTrace ();} return result ;}}
Ii. File Operation tool class in the asserts Folder:
/*** Asserts File Processing ***/public class AssertsFileUtils {private AssertsFileUtils () {}/ *** read files in the asserts directory * @ param fileName eg: "updatelog.txt" * @ return content of the corresponding file **/public static String readFileFromAssets (Context context, String fileName) throws IOException, IllegalArgumentException {if (null = context | TextUtils. isEmpty (fileName) {throw new IllegalArgumentException ("bad arguments! ");} AssetManager assetManager = context. getAssets (); InputStream input = assetManager. open (fileName); ByteArrayOutputStream output = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int length = 0; while (length = input. read (buffer ))! =-1) {output. write (buffer, 0, length);} output. close (); input. close (); return output. toString ();}/*** List all files in the Asserts folder * @ return file name List in the asserts directory ***/public static List
GetAssertsFiles (Context context) throws IllegalArgumentException {if (null = context) {throw new IllegalArgumentException ("bad arguments! ");} AssetManager assetManager = context. getAssets (); String [] files = null; try {files = assetManager. list ("");} catch (IOException e) {e. printStackTrace ();} return (null = files )? Null: Arrays. asList (files );}}