Android internal File Reading

Source: Internet
Author: User

Android File Management Method
Android uses a Linux-based file system and restricts file access and management through permission settings.
In Linux, file permissions describe the operation restrictions on files by creators, users in the same group, and other users.
X indicates executable, r indicates readable, W indicates writable, d Indicates directory, and-indicates common files.
Generate such file permissions as set by the program personnel
Android storage file type
(Internal storage) program developers can create and access private files of the program itself;
(Resource storage) You can access the original and XML files stored in the Resource Directory;
(External Storage) files can be stored on SD cards and other external storage devices.

The Android system allows applications to create private files that can only be accessed by themselves. The files are stored in the internal memory of the device, in the/data/<package name>/Files directory of Linux
Android not only supports standard Java I/O classes and methods, but also provides functions that simplify the process of reading and writing streaming files.
Fileoutputstream openfileoutput (string filename int Mode)
Fileinputstream openfileinput (string filename)
Parameter files cannot contain the slash of the description path (the storage location is fixed)
Access Mode:

Mode_private private mode, defect mode, the file can only be accessed by the File Creation Program, or programs with the same uid.
Mode_append mode. If the file already exists, add new data at the end of the file.
The global read mode of mode_world_readable allows any program to read private files.
The global write mode of mode_world_writeable allows any program to write data to a private file.

Three basic read Methods

Abstract int read (): reads a byte of data and returns the read data. If-1 is returned, the data is read to the end of the input stream.
Int read (byte [] B): reads data into a byte array and returns the actual number of bytes read. If-1 is returned, it indicates that the input stream is read to the end.
Int read (byte [] B, int off, int Len): reads data into a byte array and returns the actual number of bytes read. If-1 is returned, it indicates that the input stream is read to the end. Off specifies the starting offset position for storing data in array B, and Len specifies the maximum number of bytes to read.
Other methods
Long SKIP (long n): Skips n bytes in the input stream and returns the number of bytes actually skipped.
Int available (): the number of bytes that can be read without blocking.
Void close (): closes the input stream and releases system resources related to the stream.
Void mark (INT readlimit): place a mark at the current position of the input stream. If the number of bytes read exceeds the value set by readlimit, the stream ignores this mark.
Void reset (): returns to the previous mark.
Boolean marksupported (): test whether the current stream supports the mark and reset methods. If yes, true is returned. Otherwise, false is returned.

Three basic write Methods

Abstract void write (int B): Write a byte to the output stream.
Void write (byte [] B): write all the bytes in array B to the output stream.
Void write (byte [] B, int off, int Len): Write Len data starting from offset off in array B to the output stream.
Other methods
Void flush (): refreshes the output stream and forces the output bytes in the buffer zone to be written.
Void close (): closes the output stream and releases system resources related to the stream.

Operations on files and streams are prone to exceptions, so try-catch statements must be used.

Main core code

First, create a file.
Private final string file_name = "myfile01.txt ";
Write files
Fileoutputstream Fos = NULL; // declare a global variable
// Note that the following statements need to throw an exception. filenotfoundexception E and ioexception E
Fos = openfileoutput (file_name, context. mode_private); //

Function. The permission here is private.
String text = entrytext. gettext (). tostring (); // convert the input content to a string
FOS. Write (text. getbytes (); // convert the content converted to a string into bytes, and then write
// The following statement is written in finally
FOS. Flush (); // write the content in the cache to the file
FOS. Close (); // close the stream

Read files
Fileinputstream FCM = NULL; // defines a global variable.
FS = openfileinput (file_name); // open the file to be read
If (FCM. Available () = 0) {// checks whether the file is empty. If it is null, the system returns the result directly.
Return;
}
Byte [] readbytes = new byte [FCM. Available ()]; // converts the content in the file to bytes.
While (FCM. Read (readbytes )! =-1) {// read the file until the last read
}
String text = new string (readbytes); // converts the read bytes into strings.

The second method for reading files

String Path = "/data/CN. itcast. File/files/writeable.txt"; // obtain the file path
File file = new file (PATH); // create a file object
Fileinputstream instream = new fileinputstream (File); // read the file
Byte [] buffer = new byte [1024]; // Cache
Int Len = 0;
Bytearrayoutputstream outstream = new bytearrayoutputstream ();
While (LEN = instream. Read (buffer ))! =-1) {// until the end of reading the file
Outstream. Write (buffer, 0, Len );
}
Byte [] DATA = outstream. tobytearray (); // obtain the binary data of the object.
Outstream. Close ();
Instream. Close ();
Log. I (TAG, new string (data ));

Here is an example of reading the written file and displaying it in textview.

Step 1: Modify the layout file main. xml

View code

1 <? XML version = "1.0" encoding = "UTF-8"?>
2 <linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"
3 Android: Orientation = "vertical"
4 Android: layout_width = "fill_parent"
5 Android: layout_height = "fill_parent"
6>
7 <textview Android: Id = "@ + ID/label"
8 Android: layout_width = "fill_parent"
9 Android: layout_height = "wrap_content"
10 Android: text = "@ string/hello"
11/>
12 <edittext Android: Id = "@ + ID/entry"
13 Android: text = "input file content"
14 Android: layout_width = "fill_parent"
15 Android: layout_height = "wrap_content">
16 </edittext>
17 <linearlayout Android: Id = "@ + ID/linearlayout01"
18 Android: layout_width = "wrap_content"
19 Android: layout_height = "wrap_content">
20 <button Android: Id = "@ + ID/write"
21 Android: text = "Writing Files"
22 Android: layout_width = "wrap_content"
23 Android: layout_height = "wrap_content">
24 </button>
25 <button Android: Id = "@ + ID/read"
26 Android: text = "reading files"
27 Android: layout_width = "wrap_content"
28 Android: layout_height = "wrap_content">
29 </button>
30 </linearlayout>
31 <checkbox Android: Id = "@ + ID/APPEND"
32 Android: text = "APPEND mode"
33 Android: layout_width = "wrap_content"
34 Android: layout_height = "wrap_content">
35 </checkbox>
36 <textview Android: Id = "@ + ID/display"
37 Android: text = "file content display area"
38 Android: layout_width = "fill_parent"
39 Android: layout_height = "fill_parent"
40 Android: Background = "# ffffff"
41 Android: textcolor = "#000000">
42 </textview>
43 </linearlayout>

Step 2: Write the core code,

View code

1 package cn.edu. zwu. Tel;
2
3 Import java. Io. fileinputstream;
4 Import java. Io. filenotfoundexception;
5 import java. Io. fileoutputstream;
6 Import java. Io. ioexception;
7 Import Android. App. activity;
8 Import Android. content. context;
9 Import Android. OS. Bundle;
10 Import Android. View. view;
11 import Android. View. View. onclicklistener;
12 Import Android. widget. Button;
13 Import Android. widget. checkbox;
14 Import Android. widget. edittext;
15 Import Android. widget. textview;
16
17 public class filesavetest01activity extends activity {
18
19 private final string file_name = "myfile01.txt ";
20 private textview labelview;
21 private textview displayview;
22 private checkbox appendbox;
23 private edittext entrytext;
24 @ override
25 public void oncreate (bundle savedinstancestate ){
26 super. oncreate (savedinstancestate );
27 setcontentview (R. layout. Main );
28
29 labelview = (textview) findviewbyid (R. Id. Label );
30 displayview = (textview) findviewbyid (R. Id. Display );
31 appendbox = (checkbox) findviewbyid (R. Id. append );
32 entrytext = (edittext) findviewbyid (R. Id. Entry );
33 button writebutton = (button) findviewbyid (R. Id. Write );
34 button readbutton = (button) findviewbyid (R. Id. Read );
35 writebutton. setonclicklistener (writebuttonlistener );
36 readbutton. setonclicklistener (readbuttonlistener );
37 entrytext. selectall ();
38 entrytext. findfocus ();
39}
40
41
42 onclicklistener writebuttonlistener = new onclicklistener (){
43 @ override
44 public void onclick (view v ){
45 fileoutputstream Fos = NULL;
46 try {
47 If (appendbox. ischecked ()){
48 Fos = openfileoutput (file_name, context. mode_append );
49}
50 else {
51 Fos = openfileoutput (file_name, context. mode_private );
52}
53
54 string text = entrytext. gettext (). tostring ();
55 FOS. Write (text. getbytes ());
56 labelview. settext ("file written successfully, write length:" + text. Length ());
57 entrytext. settext ("");
58} catch (filenotfoundexception e ){
59 E. printstacktrace ();
60}
61 catch (ioexception e ){
62 E. printstacktrace ();
63}
64 finally {
65 if (FOS! = NULL ){
66 try {
67 FOS. Flush ();
68 FOS. Close ();
69} catch (ioexception e ){
70 E. printstacktrace ();
71}
72}
73}
74}
75 };
76
77 onclicklistener readbuttonlistener = new onclicklistener (){
78 @ override
79 public void onclick (view v ){
80 displayview. settext ("");
81 fileinputstream FCM = NULL;
82 try {
83 FS = openfileinput (file_name );
84 If (FS. Available () = 0 ){
85 return;
86}
87 byte [] readbytes = new byte [FCM. Available ()];
88 while (FS. Read (readbytes )! =-1 ){
89}
90 string text = new string (readbytes );
91 displayview. settext (text );
92 labelview. settext ("File Read succeeded, file length:" + text. Length ());
93} catch (filenotfoundexception e ){
94 E. printstacktrace ();
95}
96 catch (ioexception e ){
97 E. printstacktrace ();
98}
99
100}
101 };
102
103}

:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.