Summary of file read/write in Android

Source: Internet
Author: User

Summary of file read/write in Android

 

In the article on in-depth analysis of the characteristics and application scenarios of the I/O class in Java, I have introduced the I/O in Java in detail. However, if I/O in Android is the same as that in Java, it is a big mistake. In fact, they have a certain degree of consistency, but more are differences, because the file storage location in the Android system is different, the reading method is different. The following describes how to read and write files in Android:

1. Read resource files without adding permissions to the Manifest File

1. Read files from asset in resource. Note that files in asset can only be read but cannot be written.

 

public static void readFromAsset(Context context,String fileName){try{    InputStream in=context.getResources().getAssets().open(fileName);    int length=in.available();    byte[]buffer=new byte[length];        in.read(buffer);    in.close();    String content=new String(buffer,UTF-8);    ToastUtils.showShortToast(context, content);    }    catch(IOException e)    {    e.printStackTrace();    }}
2. Read the file from the raw resource. Like above, the file can only be read but cannot be written.

 

 

public static void readFromRaw(Context context,int rawResId){      InputStream in=context.getResources().openRawResource(rawResId);      try      {      int length=in.available();      byte[]buffer=new byte[length];      in.read(buffer);            String res=EncodingUtils.getString(buffer, UTF-8);            }     catch(IOException ex)     {     ex.printStackTrace();     }     finally     {     if(in!=null)     {     try     {     in.close();     }     catch(Exception e)     {     e.printStackTrace();     }     }     }}
Some people may ask what they do not want to use try (InputStream in = context. getResources (). getAssets (). open (fileName) is an autoclose method, but it is actually supported by Java SE1.7, which is not supported by the current Android version. Therefore, this method cannot be used.

 

2. Read and Write files under the application package name directory (/data/packagename)

First, read files.

 

public static void readFromPackage(Context context,String fileName){try{FileInputStream fis=context.openFileInput(fileName);int length=fis.available();byte[]buffer=new byte[length];fis.read(buffer);String content=new String(buffer,UTF-8);ToastUtils.showLongToast(context, content);}catch(IOException ex){ex.printStackTrace();}}
Next, write the file. Note that the permission should be Context. MODE_PRIVATE. Otherwise, the security red line may be violated. Currently, the following modes are used:

 

Context. MODE_PRIVATE: the default operation mode. This mode indicates that the file is private data and can only be accessed by the application itself. In this mode, the written content will overwrite the content of the original file, if you want to append the newly written content to the original file, you can use Context. MODE_APPEND;

Context. MODE_APPEND: This mode checks whether the file exists. If yes, It appends the content to the file. Otherwise, a new file is created;

Context. MODE_WORLD_READABLE: indicates that the current file can be read by other applications;

Context. WORLD_WRITEABLE: indicates that the current file can be written by other applications;

 

public static void writeToPackage(Context context,String fileName,String str){try{FileOutputStream fos=context.openFileOutput(fileName,Context.MODE_PRIVATE);byte[]buffer=str.getBytes();fos.write(buffer);fos.close();}catch(IOException ex){ex.printStackTrace();}}
3. Add the following permissions to read and write files on the SD card:

 

First, read files from the SD card.

 

     public void readFromSdcard(Context context,String fileName)     {     try     {     FileInputStream fis=new FileInputStream(fileName);     int length=fis.available();     byte[]buffer=new byte[length];     fis.read(buffer);          String content=new String(buffer,UTF-8);     ToastUtils.showLongToast(context, content);      }     catch(IOException ex)     {     ex.printStackTrace();     }     }
Then write the file to the SD card:

 

 

  public static void writeToSdCardFile(byte[]buffer,Context context,String fileName)     {     try     {     FileOutputStream fos=new FileOutputStream(fileName);     fos.write(buffer);     fos.close();     }     catch(IOException ex)     {     ex.printStackTrace();     }          }
Of course, the above is just the most basic example. As for the packaging problem after obtaining the file stream (such as using the buffer stream ), i/O class features and application scenarios in Java are described in the same article. We also recommend that you do not use the most basic file operation stream in actual use, as I have discussed in detail in previous articles, I will not discuss it here.

 

 

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.