Android file read/write
There are two ways to read and write Android files.
One is to put the txt file into the res/raw or the res/asset folder, raw files can be stored through R. raw. fileName is obtained. Files in asset can be obtained through AssetManager am = getAssets (); am. open ("FileName"); to open the file. However, if the file is stored as a capital source file, it can only be read and not written. If you want to write data, use the second method.
The second method is to read and write files from the SD card. In this way, you must first add two permission messages to AndroidManifest. xml.
Then encapsulate the file operation in a class. Here I name it FileOption and paste the Code as follows:
Package com. example. littleapplication; import java. io. bufferedReader; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. IOException; import java. io. inputStreamReader; import java. io. randomAccessFile; import java. util. vector; import android. OS. environment; import android. util. log; public class FileOption {private String fileName; private File targetFile; pr Ivate File sdCardDir; public FileOption (String fileName) throws IOException {// TODO Auto-generated constructor stubboolean mark = Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED); if (mark) {this. fileName = fileName; this. sdCardDir = environment.getexternalstoragedirectory(%%%this.tar getFile = new file(this.sdcarddir.getcanonicalpath(%%%this.filename%%%if(this.tar getFile. exists () = False=%this.tar getFile. createNewFile () ;}} else {Log. e (SDK, no memory card);} public Vector read () throws FileNotFoundException, IOException {FileInputStream FD = new FileInputStream (this. sdCardDir. getCanonicalPath () + this. fileName); BufferedReader br = new BufferedReader (new InputStreamReader (FCM); Vector res = new Vector (); String line = null; while (line = br. readLine ())! = Null) {res. add (line) ;}br. close (); return res; // TODO Auto-generated method stub} public boolean write (String add) throws IOException {RandomAccessFile raf = new RandomAccessFile(this.tar getFile, rw); raf. seek (targetFile. length (); // line feed raf. write (add. getBytes (); raf. writeChar (''); raf. close (); return true;}/** returns the total number of records * @ throws IOException * @ throws FileNotFoundException */public int size () throws FileNotF OundException, IOException {FileInputStream FCM = new FileInputStream (this. sdCardDir. getCanonicalPath () + this. fileName); BufferedReader br = new BufferedReader (new InputStreamReader (FCM); String line = null; int count = 0; while (line = br. readLine ())! = Null) {count ++;} // each of the three rows represents a data item // id title content data levelreturn count/5 ;}}