First, we will introduce how to store data using files. Activity provides the openFileOutput () method that can be used to output data to files, the specific implementation process is the same as saving data to a file in the J2SE environment.
// The path of the written file is data/cn. csdn/files/file.txt.
FileOutputStream fos = openFileOutput ("file.txt", Activity. MODE_PRIVATE );
String content = "file storage mode exercises ";
// Write in UTF-8 encoding Mode
Fos. write (content. getBytes ("UTF-8 "));
Fos. close ();
The first parameter of the openFileOutput () method is used to specify the file name. It cannot contain the path separator "/". If the file does not exist, Android will automatically create it. The created file is saved in the/data/<package name>/files directory, for example,/data/cn. itcast. action/files/itcast.txt, click "Window"-"Show View"-"Other" in the Eclipse menu, expand the android folder in the dialog box, and select the File Explorer View below, expand the/data/<package name>/files directory in the File Explorer view to view the File.
The second parameter of the openFileOutput () method is used to specify the operation mode. There are four modes: Context. MODE_PRIVATE = 0
Context. MODE_APPEND = 32768
Context. MODE_WORLD_READABLE = 1
Context. MODE_WORLD_WRITEABLE = 2
Context. MODE_PRIVATE: the default operation mode. This mode indicates that the file is private data and can only be accessed by the application itself. In this mode, the written content will overwrite the content of the original file, if you want to append the newly written content to the original file. You can use Context. MODE_APPEND.
Context. MODE_APPEND: the mode checks whether the file exists and appends the content to the file if it exists. Otherwise, a new file is created.
Context. MODE_WORLD_READABLE and Context. MODE_WORLD_WRITEABLE are used to control whether other applications have the permission to read and write the file.
MODE_WORLD_READABLE: indicates that the current file can be read by other applications; MODE_WORLD_WRITEABLE: indicates that the current file can be written by other applications.
To open a file that is private to the application in the/data/<package name>/files directory, you can use the openFileInput () method provided by Activity.
// Read the output stream
FileInputStream FCM = openFileInput ("file.txt ");
Byte buffer [] = new byte [1024];
Int byteCount = 0;
String str = "";
While (byteCount = FS. read (buffer ))! =-1 ){
// The start position of the following three parameters. How can this parameter be read?
Str + = new String (buffer, 0, byteCount, "UTF-8 ");
}
TextView TV = (TextView) findViewById (R. id. TV );
TV. setText (str );
FCM. close ();
Activity also provides the getCacheDir () and getFilesDir () methods:
The getCacheDir () method is used to obtain the/data/<package name>/cache directory.
The getFilesDir () method is used to obtain the/data/<package name>/files directory.
Author w_l_j