The method for reading/writing files in Android is the same as that in Java I/O. openfileinput () and openfileoutput () methods are provided to read files on the device. However, by default, files cannot be different.ProgramShared between the two methods, the above two methods only support reading files under the application directory, reading files not under its own directory will throw a filenotfoundexception exception. The created file is stored in the/data/<package name>/Files directory.
Return Value |
Function |
Remarks |
Fileinputstream |
Openfileinput (string name) |
Open the output stream of the specified private file. Name: The name of the file to be opened. It cannot contain path separators. |
Fileoutputstream |
Openfileoutput (string name, int Mode) |
Open the output stream of the specified private file. Name: The name of the file to be opened. It cannot contain path separators. Mode: Operation mode. The default value is 0 or mode_private. Other modes include: L mode_append: append L mode_world_readable L mode_world_writeable If the specified file does not exist when you call this function, a blank file is automatically created. By default, the content of the original file will be overwritten during writing. To append the newly written content to the end of the original file, you can specify the mode as context. mode_append. |
Boolean |
Deletefile (string name) |
Deletes a specified object. Name: The name of the file to be deleted. It cannot contain a path. |
String [] |
Filelist () |
Returns the file names of all private files related to the application package that calls the context related to this function. |
CodeCase:
Read files:
// Stores the byte stream of read data.
Bytearrayoutputstream stream = New Bytearrayoutputstream ();
Fileinputstream FCM = openfileinput(“text1.txt ");
Byte [] Buffer = New Byte [1024];
Int Len =-1;
While (LEN = instream. Read (buffer ))! =-1 ){
Stream. Write (buffer, 0, length );
}
Stream. Close ();
FCM. Close (); // Close input stream
Text. settext (stream. tostring ()); // Displayed
Write File:
Fileoutputstream Fos = openfileoutput(export text1.txt ", mode_append );
FOS. Write (text. gettext (). tostring (). getbytes ());
FOS. Close (); // Close output stream