personal Learning and collation, if there are deficiencies, please feel free. Reprint Please specify:@CSU-max
read and write files in this Application Data folderThis method reads and writes files in the/data/data/< application package name > Span style= "font-family: ' Microsoft Yahei '; line-height:21px "> &NBSP is provided in the android; openfileinput (string filename ) and openfileoutput (String fileName, int mode openfileinput (string filename open File input stream Openfileoutput ( String fileName, int mode) to open the file output stream Note:the parameter inopenfileoutput (String fileName, int mode) mode specifies the form in which the file opens: mode_private: The file can only be read and written by the current program mode_append: Open File in Append mode, application can append content to file mode_world_readable: The contents of this file can be read by other applications mode_world_writeable: The contents of this file can be read and written by other applications Example:This example program interface file Input section has an input box and a button, click the button can be entered in the input box to write the information entered into the specified file, the Reading section has a text box and a button, click the button text box will display the contents of the specified file. read: write:
Verify write:
Instance code:
Package Com.example.filedemo;import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.printstream;import Android.os.bundle;import Android.app.activity;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import android.widget.textview;/** * * @author Csumax * @version 1.0 2014-4-24 */public class Mainactivity extends Activity {pri Vate Button bt_main_in; Write File button private button bt_main_out; Read File button private EditText et_main_in;//input text box private TextView tv_main_out;//display file contents @overrideprotected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.main); bt_main_in = (Button) This.findviewbyid (r.id.bt_main_in); bt_main_out = (Button) This.findviewbyid (r.id.bt_main_out); et_main_in = ( EditText) This.findviewbyid (r.id.et_main_in); tv_main_out = (TextView) This.findviewbyid (r.id.tv_main_out);// Click the button to write the contents of the input box to the file Bt_main_in.setonclicklistener (new OnclicklistenER () {@Overridepublic void OnClick (View v) {String fileName = "Demo.txt"; String text = Et_main_in.gettext (). toString (); WriteToFile (text, fileName); Et_main_in.settext ("");}}); /Click the button to read the contents of the file and display it in the text box Bt_main_out.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) { String fileName = "Demo.txt"; Tv_main_out.settext (ReadFromFile (FileName));}}); /** * Read File * * @param fileName * @return */public string readfromfile (string filename) {try {FileInputStream FIS = openfi Leinput (FileName); byte[] bytes = new byte[1024]; StringBuffer sb = new StringBuffer (), int i = 0;i = Fis.read (bytes), if (i > 0) {sb.append (New String (bytes, 0, i));} return sb.tostring ();} catch (Exception e) {e.printstacktrace ();} return null;} /** * Write to File * * @param text * Write content * @param filename * file name */public void WriteToFile (String te XT, String FileName) {try {//mode_append mode write, i.e. append mode fileoutputstream fos = Openfileoutput (FileName, mode_append); PrintStream PS = new PrintStream(FOS);p s.println (text);p s.close ();} catch (Exception e) {e.printstacktrace ();}}}
the Demo.txt file in the program can be seen through the/data/data/< application package name >/files/demo.txt in the file Explorer, as shown (due to the large number of unrelated files, it is divided into two images UP):
read files in a resource file
here, for example, read the resource raw file, create a new raw folder under the Res folder and copy the previous Demo.txt file into it.
Main code:
public class Readfileutil {public static string Readfromraw (context context, int id) { string str = ""; try { //Get input stream InputStream is = Context.getresources (). Openrawresource (ID); int length = is.available (); byte[] bytes = new Byte[length]; int i = 0; i = Is.read (bytes); if (i > 0) { //set encoding str = encodingutils.getstring (bytes, "UTF-8"); } Is.close (); return str; } catch (Exception e) { //Todo:handle Exception } return null;} }
Test Code:
public class Readertest extends Androidtestcase { private static final String TAG = "Readertest"; public void Testreadfromraw () { log.i (TAG, "---------------"); String str = "Failed"; str = Readfileutil.readfromraw (GetContext (), R.raw.demo); LOG.I (TAG, "========>" + str + "<========");} }
Note: Files under the resource file are accessed through the ID identified in the R file, so r.raw. Demo .
read and write files on SD card
Sometimes we store some data on the SD card, and now let's simulate, adding the previous/mnt/sdcard/directory to the File Explorer view . Demo.txt file, now try to read the information in the file and write the information to it.
Main code:
public class Readfileutil {public static string Readfromsdcard (String fileName) {string str = ""; try {fileinputstream fis = new FileInputStream (fileName); int length = fis.available (); byte[] bytes = new Byte[length]; int i = 0; i = Fis.read (bytes); if (i > 0) {//set encoding str = encodingutils.getstring (bytes, "UTF-8"); } fis.close (); return str; } catch (Exception e) {//Todo:handle Exception} return null; /** *-Note that when writing information to a file in an SD card, the appropriate permissions are added to the Androidmanifest.xml file--*/public static void Writetosdcard (String text, String FileName {The second parameter of the try {//constructor method represents an append pattern fileoutputstream fos = new FileOutputStream (filen Ame, True); byte[] bytes = Text.getbytes (); Fos.write (bytes); Fos.close (); } catch (Exception e) {E.priNtstacktrace (); } } }
Test Code:
public class Readertest extends Androidtestcase { private static final String TAG = "Readertest"; public void Testreadfromsdcard () { log.i (TAG, "---------------"); String str = "Failed"; str = Readfileutil.readfromsdcard ("/mnt/sdcard/demo.txt"); LOG.I (TAG, "========>" + str + "<========"); } public void Testwritetosdcard () { log.i (TAG, "---------------"); String Text = "Max"; Readfileutil.writetosdcard (text, "/mnt/sdcard/demo.txt");} }
Note:generally read and write files in this application to use openfileinput and Openfileoutput, while reading and writing files in the SD card requires the use of Fileinputstre A and FileOutputStream. By default, the files in the SD card are read-only, so you need to include the appropriate permissions to write data to the SD card.
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission Android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
***************************************************************************
* Reprint Please specify source: @CSU-max Http://blog.csdn.net/csu_max *
***************************************************************************