There are two ways to read and write Android files
one is to txt file as resource file on or res/asset raw files can be passed r.raw.filename obtained, asset files can be passed assetmanager am = getassets (); Am.open ( " FileName ");
The second method reads and writes files from the SD card so that the first thing to do is to add two permission messages to the androidmanifest.xml
<!--Create and delete files in SDcard permissions-- <uses-permission android:name= "android.permission.MOUNT_UNMOUNT_ Filesystems "/> <!--writing data to SDcard permissions-- <uses-permission android:name=" Android.permission.WRITE _external_storage "/>
Then wrap the file operation in a class, where I name it fileoption, first 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;private file Sdcarddir; Public fileoption (String fileName) throws IOException {//TODO auto-generated constructor Stubboolean mark = Environment.g Etexternalstoragestate (). Equals (environment.media_mounted); if (Mark) {this.filename = Filename;this.sdcarddir = Environment.getexternalstoragedirectory (); this.targetfile = new File (This.sdCardDir.getCanonicalPath () + This.filename); if (this.targetFile.exists () ==false) {this.targetFile.createNewFile ();}} ELSE{LOG.E ("SDK", "No Memory Card");}} Public Vector Read () throws FileNotFoundException, IOException {fileinputstream fis = new FileInputStream (this.sdcarddir . GetcanoniCalpath () +this.filename); BufferedReader br = new BufferedReader (new InputStreamReader (FIS)); 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.targetfile, "RW"); Raf.seek (Targetfile.length ());//NewLine Raf.write ( Add.getbytes ()); Raf.writechar (' \ n '); Raf.close (); return true;} /** returns the total number of records * @throws IOException * @throws filenotfoundexception */public int size () throws FileNotFoundException, IOE Xception{fileinputstream fis = new FileInputStream (This.sdCardDir.getCanonicalPath () +this.filename); BufferedReader br = new BufferedReader (new InputStreamReader (FIS)); String line = Null;int count = 0;while (line = Br.readline ())!=null) {count++;} Each three rows represents a data item//ID title content Data levelreturn COUNT/5;}}
Android file read/write