Import Java.io.FileInputStream; Import Java.io.FileOutputStream; Import Java.io.InputStream; Import Org.apache.http.util.EncodingUtils; Import android.app.Activity; public class FileAccess {/** *, file access under Private folder (/data/data/package name/files) * * @param fileName * @param mess Age */public void Writefiledata (string fileName, String message) {try {FileOutputStream fou t = openfileoutput (fileName, mode_private); byte[] bytes = Message.getbytes (); Fout.write (bytes); Fout.close (); } catch (Exception e) {e.printstacktrace (); }}/** *//Read file under./data/data/Package Name/files/* * @param fileName * @return */public String R Eadfiledata (String fileName) {String res = ""; try {fileinputstream fin = openfileinput (fileName); int length = fin.available (); byte[] buffer = new Byte[length]; Fin.read (buffer); res = encodingutils.getstring (buffer, "UTF-8"); Fin.close (); } catch (Exception e) {e.printstacktrace (); } return res; }/** * Write, read sdcard directory files, to use FileOutputStream, can not be used Openfileoutput * different points: Openfileoutput is compiled in raw, Fileoutputstrea M is any file can be * @param fileName * @param message *///////write the file under the/mnt/sdcard/directory public void Writefilesdcard (S Tring filename, String message) {try {//FileOutputStream Fout = openfileoutput (filename, Mode_priva TE); FileOutputStream fout = new FileOutputStream (fileName); byte[] bytes = Message.getbytes (); Fout.write (bytes); Fout.close (); } catch (Exception e) {e.printstacktrace (); }}//Read the file under the/mnt/sdcard/directory public string Readfilesdcard (string fileName) {String res = ""; try {fileinputstream fin = new FileInputStream (fileName); int length = fin.available (); byte[] buffer = new Byte[length]; Fin.read (buffer); res = encodingutils.getstring (buffer, "UTF-8"); Fin.close (); } catch (Exception e) {e.printstacktrace (); } return res; }/** * Second, get the file from the Raw folder in resource and read the data (resource file can only read and write) * * @param fileinraw * @return */Public S Tring Readfromraw (int fileinraw) {String res = ""; try {InputStream in = Getresources (). Openrawresource (Fileinraw); int length = in.available (); byte[] buffer = new Byte[length]; In.read (buffer); res = encodingutils.getstring (buffer, "GBK"); res = new String (buffer, "GBK"); In.close (); } catch (Exception e) {e.printstacktrace (); } return res; }/** * Three, get the file from the asset and read the data (resource file can only read and write) * * @param fileName * @return */public string Readfromasset (string fileName) {String res = ""; try {InputStream in = Getresources (). Getassets (). open (FileName); int length = in.available (); byte[] buffer = new Byte[length]; In.read (buffer); res = encodingutils.getstring (buffer, "UTF-8"); } catch (Exception e) {e.printstacktrace (); } return res; } }
Android TXT file read/write (read resource file, read private and SD file method)