Files in Android are placed in different locations, and they are read in some different ways.
In this paper, the reading of resource files in Android, the reading of data area files, the reading of SD card files and the ways and methods of Randomaccessfile are organized. For reference.
One, the resource file reads:
1) Read the file data from resource raw:
String res = ""; try{ //Get raw data stream in the resource inputstream in = Getresources (). Openrawresource (r.raw.test); Get the size of the data int length = in.available (); byte [] buffer = new Byte[length]; Read Data in.read (buffer); Depending on the encoding type of test.txt, choose the appropriate encoding, if not adjusted will be garbled res = encodingutils.getstring (buffer, "BIG5"); Close in.close (); } catch (Exception e) { e.printstacktrace ();
2) Read the file data from the resource asset
String fileName = "Test.txt"; File name String res= ""; try{ //Gets the asset data stream in the resource inputstream in = Getresources (). Getassets (). open (fileName); int length = in.available (); byte [] buffer = new Byte[length]; In.read (buffer); In.close (); res = encodingutils.getstring (buffer, "UTF-8"); } catch (Exception e) { e.printstacktrace ();
Second, read and write the/data/data/< application name > directory files:
Write Data public void WriteFile (String filename,string writestr) throws ioexception{ try{ fileoutputstream fout = Openfileoutput (FileName, mode_private); byte [] bytes = Writestr.getbytes (); Fout.write (bytes); Fout.close (); } catch (Exception e) { e.printstacktrace (); }}//Read data public String ReadFile (string fileName) throws ioexception{< C9/>string res= ""; try{ fileinputstream fin = openfileinput (fileName); int length = fin.available (); byte [] buffer = new Byte[length]; Fin.read (buffer); res = encodingutils.getstring (buffer, "UTF-8"); Fin.close (); } catch (Exception e) { e.printstacktrace (); } return res; }
Third, read and write the files in the SD card. This is the file under the/mnt/sdcard/directory:
Write data to SD file public void Writefilesdcardfile (String filename,string write_str) throws ioexception{ try{ FileOutputStream fout = new FileOutputStream (fileName); byte [] bytes = Write_str.getbytes (); Fout.write (bytes); Fout.close (); } catch (Exception e) { e.printstacktrace (); } } Read the file public in SD string Readfilesdcardfile (String fileName) throws ioexception{ string res= ""; try{ fileinputstream fin = new FileInputStream (fileName); int length = fin.available (); byte [] buffer = new Byte[length]; Fin.read (buffer); res = encodingutils.getstring (buffer, "UTF-8"); Fin.close (); } catch (Exception e) { e.printstacktrace (); }
Iv. use the file class to read and write files:
Read file public string Readsdfile (String fileName) throws IOException { file File = new file (fileName); FileInputStream fis = new FileInputStream (file); int length = fis.available (); byte [] buffer = new Byte[length]; Fis.read (buffer); res = encodingutils.getstring (buffer, "UTF-8"); Fis.close (); return res; } Write file public void Writesdfile (string fileName, String write_str) throws ioexception{ File File = new file (fileName); C11/>fileoutputstream fos = new FileOutputStream (file); byte [] bytes = Write_str.getbytes (); Fos.write (bytes);
V. In addition, the file class has some of the following common operations:
String Name = File.getname (); Get the name of the file or folder: String Parentpath = File.getparent (); Gets the parent directory of the file or folder string path = File.getabsoultepath ();//absolute path via string path = File.getpath ();//relative path via File.createnewfile ();// Set up file file.mkdir ();//Create Folder file.isdirectory ();//Determine if file or folder file[] files = file.listfiles (); Lists all file and folder names under Folders File.renameto (dest); Modify folder and file name File.delete (); Delete a folder or file
VI. Use Randomaccessfile to read and write files:
The use of randomaccessfile is more flexible, more functions, you can use a similar way to seek to jump to any location of the file, starting from the current position of the file indicator read and write.
It has two methods of construction
New Randomaccessfile (F, "RW");//read/write mode
New Randomaccessfile (F, "R");//read-only mode
Use case:
/* * Program features: Demonstrates the operation of the Randomaccessfile class, while implementing a file copy operation. */import java.io.*; public class Randomaccessfiledemo {public static void main (string[] args) throws Exception {Randomaccessfile file = New Randomaccessfile ("File", "RW"); The following writes data to the file File.writeint (20);//4 bytes file.writedouble (8.236598);//8 bytes File.writeutf ("This is a UTF string");//This The length is written at the first two bytes of the current file pointer, Readshort () can be read File.writeboolean (true), or 1 bytes file.writeshort (395);//2 bytes File.writelong (2 325451L);//accounted for 8 bytes File.writeutf ("Again a UTF string"); File.writefloat (35.5f);//accounted for 4 bytes file.writechar (' a ');//accounted for 2 bytes file.seek (0);//Set the position of the file pointer to the beginning of the file//below read data from file , note the position of the file pointer System.out.println ("—————— read data from the file specified location ——————"); System.out.println (File.readint ()); System.out.println (File.readdouble ()); System.out.println (File.readutf ()); File.skipbytes (3);//Skips the file pointer over 3 bytes, skipping a Boolean and short values in this example. System.out.println (File.readlong ()); File.skipbytes (File.readshort ()); Skip the file "anotherUTF string "occupies bytes, note that the Readshort () method moves the file pointer, so do not add 2. System.out.println (File.readfloat ()); The following demo file copy Operation System.out.println ("—————— file to FileCopy ——————"); File.seek (0); Randomaccessfile filecopy=new randomaccessfile ("FileCopy", "RW"); int len= (int) file.length ();//Get file Length (bytes) byte[] B=new Byte[len]; File.readfully (b); Filecopy.write (b); System.out.println ("Copy done! "); } }
Vii. can you implement a seek-like method when reading a resource file to jump to any location in the file, starting at the specified location and reading the specified number of bytes?
The answer is yes.
The following functions are available in both FileInputStream and InputStream:
Public long Skip (long byteCount); Skips n bytes from a data stream public int read (byte[] buffer, int offset, int length); Reads the length data from the data stream where offset begins with buffer. Offset is relative to the starting position of the buffer, not the data stream.
You can use these two functions to implement a seek-like operation, see the following test code:
Where Read_raw is a txt file, stored in the raw directory. The contents of the Read_raw.txt file are: "Abcdefghijklmnopqrst" public String getrawstring () throws IOException {String str = null;i Nputstream in = Getresources (). Openrawresource (r.raw.read_raw); int length = In.available (); byte[] buffer = new byte[ Length];in.skip (2); Skips two bytes of in.read (buffer,0,3); Read three bytes of In.skip (3); Skips three bytes of in.read (buffer,0,3); Read three bytes//last str= "IJK" str = encodingutils.getstring (buffer, "BIG5"); In.close (); return str;}
As you can see from the example above, the Skip function is somewhat similar to the seek operation in C, but there are some differences between them.
It is important to note that:
1. The skip function always starts at the current position. The return value of the function should be judged in the actual application.
2, the Read function is always the current position to begin reading.
3. Alternatively, you can use the Reset function to reset the file's current position to 0, which is where the file starts.
How do I get the current location of the file?
I did not find the relevant functions and methods, do not know how to get the current position of the file, it seems that it is not too important.
Eight, how to get InputStream from the FileInputStream?
public string Readfiledata (String fileName) throws ioexception{ string res= ""; try{ fileinputstream fin = new FileInputStream (fileName); InputStream in = new Bufferedinputstream (FIN); ... } catch (Exception e) { e.printstacktrace (); }}
Nine, the size of the APK resource file can not exceed 1M, if more than what to do? We can then copy this data to the database directory and then use it again. The code to copy the data is as follows:
public boolean Assetscopydata (String Strassetsfilepath, String Strdesfilepath) {Boolean bissuc = true; InputStream inputstream = null; OutputStream outputstream = null; File File = new file (Strdesfilepath); if (!file.exists ()) {try {file.createnewfile (); Runtime.getruntime (). EXEC ("chmod 766" + file); } catch (IOException e) {bissuc = false; }}else{//existence return true; try {InputStream = Getassets (). open (Strassetsfilepath); OutputStream = new FileOutputStream (file); int nlen = 0; byte[] buff = new byte[1024*1]; while (Nlen = Inputstream.read (buff)) > 0) {outputstream.write (buff, 0, Nlen); }//completion} catch (IOException e) {bissuc = false; }finally{try {if (OutputStream! = NULL) {outputstream.close (); } if (InputStream! = null) {inputstream.close (); }} catch (IOException e) {bissuc = false; }} return bissuc; }
Summarize:
1. There are two kinds of resource files in apk, which are used in two different ways.
Raw uses inputstream in = Getresources (). Openrawresource (R.raw.test);
Asset uses inputstream in = Getresources (). Getassets (). open (FileName);
This data can only be read and cannot be written. More importantly, the file size under this directory cannot exceed 1M.
Also, it is important to note that you need to add throws IOException to the function name when using InputStream.
2, the files in the SD card use FileInputStream and FileOutputStream for file operation.
3, stored in the data area (/data/data/.) Files can only be manipulated using Openfileoutput and Openfileinput.
Note You cannot use FileInputStream and FileOutputStream for file operations.
4, the Randomaccessfile class is limited to file operation, cannot access other IO devices. It can jump to any location of the file and start reading and writing from the current position.
5, InputStream and FileInputStream can use the Skip and read (Buffre,offset,length) functions to implement random reads of the file.
Reference: http://blog.csdn.net/ztp800201/article/details/7322110
Android-File read and write operations summary