File to save the data, save the path to/data/data/<packagename>/files/. There are two modes: Mode_private and Mode_append, where mode_private is the default mode of operation, indicating that when the same file name is specified, the content that is written overwrites the contents of the original file, and Mode_append This means that if the file already exists, append content to the file and create a new file if it does not exist.
1 Public voidSave () {2String data = "Data to save";3FileOutputStream out =NULL;4BufferedWriter writer =NULL;5 Try {6out = Openfileoutput ("Data"), context.mode_private);7writer =NewBufferedWriter (NewOutputStreamWriter (out));8 writer.write (data);9}Catch(IOException e) {Ten e.printstacktrace (); One}finally { A Try { - if(Writer! =NULL) { - writer.close (); the } -}Catch(IOException e) { - e.printstacktrace (); - } + } -}
1 PublicString Load () {2FileInputStream in =NULL;3BufferedReader reader =NULL;4StringBuilder content =NewStringBuilder ();5 Try {6in = Openfileinput ("Data");7Reader =NewBufferedReader (NewInputStreamReader (in));8String line = "";9 while(line = Reader.readline ())! =NULL) {Ten Content.append (line); One } A}Catch(IOException e) { - e.printstacktrace (); -}finally { the if(Reader! =NULL) { - Try { - reader.close (); -}Catch(IOException e) { + e.printstacktrace (); - } + } A } at returncontent.tostring (); -}
The first way for Android to read and write files (file mode)