I. There are three types of File Reading locations in Android:
First: read data from asset:
// Method: get the file from asset and read the data Public String getfromasset (string filename) {string result = ""; try {inputstream in = getresources (). getassets (). open (filename); // obtain the input stream int length = in from the file in assets. available (); // get the object's byte [] buffer = new byte [length]; // create a byte array in. read (buffer); // read the data in the file to the byte array result = encodingutils. getstring (buffer, encoding); // convert the byte array to a string in the specified format} catch (ioexception e) {e. printstacktrace (); // catch an exception and print} catch (exception e) {e. printstacktrace ();} return result ;}
Type 2: read data from the raw folder in the resource:
// Method: Obtain the file from the raw folder in the resource and read the data Public String getfromraw (string filename) {string result = ""; try {inputstream in = getresources (). openrawresource (R. raw. test1); // obtain the input stream int length = in from the raw file in resources. available (); // get the object's byte [] buffer = new byte [length]; // create a byte array in. read (buffer); // read the data in the file to the byte array result = encodingutils. getstring (buffer, encoding); // converts a byte array to a string in the specified format. close (); // close the input stream} catch (ioexception e) {e. printstacktrace (); // catch an exception and print} catch (exception e) {e. printstacktrace ();} return result ;}
Third: read data from system files or SD cards:
// Method: Open the specified file, read its data, and return the string object Public String readfiledata (string filename) {string result = ""; try {fileinputstream fin = openfileinput (filename );// Obtain the fileinputstream object int length = fin. Available ();// Obtain the object Length byte [] buffer = new byte [length]; // Create a byte array for reading data fin. Read (buffer); // read the file content into the byte array result = encodingutils. getstring (buffer, encoding );// Convert the byte array to the specified string fin. Close (); // close the file input stream} catch (exception e) {e. printstacktrace ();// Capture exceptions and print} return result;// Return the read data string }}
2. Compared with reading data, writing data to a file is missing, and only system files can be written to the SD card file.
The two methods are common:
Void writedata (string filename, string MSG) {try {fileoutputstream Fos = This. openfileoutput (filename, mode_private); byte [] Buf = MSG. getbytes (); FOS. write (BUF); FOS. close ();} catch (filenotfoundexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();}}
OK. That's all!