File read and write operation and skill summary of Android programming "Classic Collection" _android

Source: Internet
Author: User
Tags file copy parent directory

An example of this article summarizes the Android file read and write operation. Share to everyone for your reference, specific as follows:

Files in Android are placed in different locations, and they are read in a number of different ways.
In this paper, the ways and methods of reading the resource files, reading the data area files, reading and randomaccessfile the SD card files are sorted out in Android. For reference.

One, the resource file reads:

1 read the file data from the RAW resource:

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);
  According to Test.txt encoding type to 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{
  //Get 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/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{
 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;
}

Read and write the files in SD card. The file below the/mnt/sdcard/directory:

Write data to the file in SD-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 files in SD to public
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 ();
    }
    return res;
}

Using 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 (filen AME);
    FileOutputStream fos = new FileOutputStream (file);
    byte [] bytes = Write_str.getbytes ();
    Fos.write (bytes);
    Fos.close ();
}

Five, in addition, the file class also has some of the following common operations:

String Name = File.getname (); Get the name of the file or folder:
string parentpath = File.getparent ();//Get the file or folder's parent directory
String path = File.getabsoultepath ();// Absolute path via
String path = File.getpath ()///relative path via
file.createnewfile ();//Create File
file.mkdir ();//Create Folder
File.isdirectory (); Judgment is file or folder
file[] files = file.listfiles ();//List all file and folder names
File.renameto (dest) under the folder;//Modify folder and file name
File.delete (); Delete a folder or file

Vi. using Randomaccessfile to read and write documents:

Randomaccessfile is more flexible and more versatile, and can be used in a way that allows you to jump to any location in a file and start reading and writing from the current location of the file indicator.

It has two methods of construction

New Randomaccessfile (F, "RW");/read-write mode
new Randomaccessfile (F, "R");/read-only mode

Use case:

* * Program function: Demonstrated 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 = NE
 W randomaccessfile ("File", "RW"); The following writes data to the file File.writeint (20),//occupies 4 bytes file.writedouble (8.236598),//occupies 8 bytes File.writeutf ("This is a UTF string"); This length is written in the first two bytes of the current file pointer, available readshort () to read File.writeboolean (true), or 1 bytes file.writeshort (395),//2 bytes File.writelong (
 2325451L);//Account for 8 bytes File.writeutf ("Again a UTF string"); File.writefloat (35.5f);//4 bytes File.writechar (' a ');//2 bytes file.seek (0);//Set the file pointer position to the beginning of the file//below, read the data from the file.
 Note the location of the file pointer System.out.println ("—————— read data from a file file ——————");
 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, in this case skipping a Boolean and a short value.
 System.out.println (File.readlong ()); File.skipbytes (File.readshort ());
 Skips the byte of "another UTF string" in the file, note that the Readshort () method moves the file pointer, so you do not need to 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 complete!")
 ");

 }
}

Vii. is it possible to read a resource file in such a way that you can jump to any location in the file and read the specified number of bytes from the specified location?
The answer is yes.

The following functions are available in both FileInputStream and InputStream:

Public long Skip (long byteCount); Skips n bytes public
int read (byte[] buffer, int offset, int length) from the data stream; the position at which the offset of the buffer begins to be read from the data stream. Offset is the starting position relative to 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;
  InputStream in = Getresources (). Openrawresource (R.raw.read_raw);
  int length = in.available ();
  byte[] buffer = new Byte[length];
  In.skip (2); Skip two bytes
  in.read (buffer,0,3),//Read three bytes
  In.skip (3),//Skip three bytes
  in.read (buffer,0,3),//Read three bytes
  // Finally str= "IJK"
  str = encodingutils.getstring (buffer, "BIG5");
  In.close ();
  return str;
}

From the example above you can see that the skip function is somewhat similar to the seek operation in C, but there are some differences between them.

It is to be noted that:

1. The skip function always starts at the current position. The return value of the function should be judged in practical application.

2, the Read function is always beginning to read the current position.

3, in addition, you can also use the Reset function to reset the current position of the file to 0, which is the beginning of the file location.

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 location of the file, seemingly it is not too important.

Viii. how to get InputStream from 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, apk resource file size can not exceed 1M, if more than how to do? We can then copy this data to the database directory and 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{//exists 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, using two different ways to open.

Raw USE:

InputStream in = Getresources (). Openrawresource (R.raw.test);

Asset use:

InputStream in = Getresources (). Getassets (). open (FileName);

This data can only be read and cannot be written to. More importantly, the file size in this directory cannot exceed 1M.

At the same time, it should be noted that when using InputStream, you need to add throws IOException after the function name.

2, SD card files using FileInputStream and FileOutputStream for the operation of the file.

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 operations and cannot access other IO devices. It can jump to any location in the file and start reading and writing from the current location.

5, InputStream and FileInputStream can use the Skip and read (Buffre,offset,length) functions to implement random reads of files.

For more information on Android-related content readers can view the site topics: "Android File Operation tips Summary", "Android programming development of the SD card operation Summary", "Android Development introduction and Advanced Course", "Android Resources Operating Skills summary", " Android View tips Summary and a summary of the use of Android controls

I hope this article will help you with the Android program.

Related Article

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.