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. |
ExampleCode:
|
// Read the file
Fileinputstream FCM = openfileinput(“text1.txt ");
... ...
FCM. Close (); // close the input stream
// Write a file
Fileoutputstream Fos = openfileoutput(export text1.txt ", mode_append );
... ...
FOS. Close (); // close the output stream |
If you need to load the content of a file to initialize the program during application development, you can set the file to static before compiling the program) put the file in the Res/raw/mydatafile directory, and then use resources. openrawresource (R. raw. file Name) This method returns an inputstream object. The sample code is as follows:
|
Resources myresources = getresources ();
Inputstream myfile = myresources. openrawresource (R. Raw. myfilename ); |