Summary of reading and writing methods for files in the memory of Android phones
Summary of reading and writing methods for files in the memory of Android phones
This article describes how to read and write files in the memory of Android phones. The example summarizes the skills related to file read and write operations in Android, which is very useful. For more information, see:
How can I read and write the file data in the mobile phone memory?
Context provides a method to open the file I/O stream in the data folder of the application, as follows:
?
1 |
FileInputStream openFileInput (String name) |
Open the data stream corresponding to the name file in the data folder of the application
?
1 |
FileOutputSream openFileOutput (String name, int mode) |
Open the output stream corresponding to the name file in the application data folder. mode specifies the mode in which the file is opened. There are four modes:
① MODE_PRIVATE (the file can only be read and written by the current application)
② MODE_APPEND (open in append mode and Append content to the file)
③ MODE_WORLD_READABLE (the file content can be read by other applications)
④ MODE_WORLD_WRITEABLE (the file content can be written by other applications)
Read files:
Assume that name is the name of the file to be opened.
?
1 2 3 4 5 6 7 8 9 |
FileInputStream f = openFileInput (name ); Byte [] buf = new byte [1, 1024]; Int hasRead = 0; StringBuilder sb = new StringBuilder (""); While (hasRead = f. read (buf)> 0 )) { Sb. append (new String (buf, 0, hasRead )); } F. close (); |
Get the file content string:
?
Write File:
Assume that the string to be written is content
?
1 2 3 4 |
FileOutputStream f = openFileOutput (name, MODE_APPEND ); PrintStream temp = new PrintStream (f ); Temp. println (content ); Temp. close (); |
Note: application data files are stored in/data/datea by default. In the/files directory, use the openFileInput and openFileOutput methods to open the file input stream. During the output stream, all files in the data folder of the application are opened, that is, files in the memory of the mobile phone, instead of files in the SD card.
I hope this article will help you design your Android program.