Often need to read "/res/raw" and "/asserts" folders under the file, simply written as a tool to facilitate later use.
One, the raw folder under the file Operation Tool class:
/** * Raw folder File Processing Tool class * * */public class Rawfileutils {private Rawfileutils () {}/** * read files under Raw folder * @param resourceId File resource ID under Raw folder * @return File contents * */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);//Gets the number of bytes of the file int l Ength = Inputstream.available ();//Create a byte array byte[] buffer = new byte[length];//read the data in the file into a byte array inputstream.read (buffer result = encodingutils.getstring (buffer, "utf-8");} catch (Exception e) {e.printstacktrace ();} return result;}}
Second, the asserts folder under the file Operation Tool class:
/** * asserts file processing * * */public class Assertsfileutils {private Assertsfileutils () {}/** * read files in asserts directory * @param Filena Me eg: "updatelog.txt" * @return the contents of the corresponding file * * */public static string Readfilefromassets (context context, String FileName) t Hrows 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 under the asserts folder * @return List of file names in the asserts directory * * */public static list<string> Getasserts Files (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); }}
Android reads files under asserts and raw folders