There are several APIs available in Android for file operations in addition to Java's Basic library rollup of Io, file, etc.
1, the context class provides the Openfileoutput () and Openfileinput () two methods to obtain the IO stream, and then can be related to read and write operations.
The parameters of the operation mode of a file in a write operation are several constants provided by the context: mode_private, overwriting file, default mode;
Mode_append, append content, does not exist on the new.
Read file
PublicString Load (Context context,string fileName) {FileInputStream is=NULL; BufferedReader Reader=NULL; StringBuilder result=NewStringBuilder (); Try{ is=Context.openfileinput (fileName); Reader=NewBufferedReader (NewInputStreamReader (IS)); String L=""; while((L=reader.readline ())! =NULL) {result.append (L); } } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally { if(reader!=NULL) { Try{reader.close (); } Catch(IOException e) {e.printstacktrace (); } } } returnresult.tostring (); }
Write file
Public BooleanWrite (Context context,string filename,string content) {FileOutputStream OS=NULL; BufferedWriter writer=NULL; Try{OS=Context.openfileoutput (Filename,context. Mode_append); Writer=NewBufferedWriter (Newoutputstreamwriter (OS)); Writer.write (content); return true; } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally { if(writer!=NULL) { Try{writer.close (); } Catch(IOException e) {e.printstacktrace (); } } } return false; }
2, the following use of the four environment method, get the current running environment of four different directories, return a file object, we can according to this file
Object for new, write, read, and other operations. For different manufacturers, the Access API for SD card phone memory may be modified, these need actual situation, practical analysis.
LOG.I ("info", "getdatadirectory ()" +environment.getdatadirectory (). GetAbsolutePath ()); LOG.I ("info", "getrootdirectory ()" +environment.getrootdirectory (). GetAbsolutePath ()); LOG.I ("info", "getexternalstoragedirectory ()" +environment.getexternalstoragedirectory (). GetAbsolutePath ()); LOG.I ("info", "getexternalstoragepublicdirectory ()" +environment.getexternalstoragepublicdirectory (" BasePath "). GetAbsolutePath ());
Android file access