Using SDcard to read files in Android _android

Source: Internet
Author: User
Tags file permissions

Usually we need to store on the phone for audio, video and so on large files, previously learned to use file for storage (using the file operation to store); Because of the small storage space of the phone itself, we need to store the file in SDcard, Today I also learned how to use the SDcard storage in Android;

First, if you want to use SDcard for storage in your program, we have to do the following permissions setting in the Androidmanifset.xml file:

The right to join the access SDcard in Androidmanifest.xml is as follows:

<!--Create and delete file permissions in SDcard-->
<uses-permission android:name= "android.permission.MOUNT_UNMOUNT_ Filesystems "/>
<!--write data permissions to SDcard-->
<uses-permission android:name=" Android.permission.WRITE _external_storage "/>

Then we use SDcard to read and write, we use a few static methods below the Environment class

1:getdatadirectory () gets to the data directory in Androi

2:getdownloadcachedirectory () gets to the downloaded cache directory

3:getexternalstoragedirectory () gets to the externally stored directory generally refers to the SDcard

4:getexternalstoragestate () Gets the current state of the external setting generally refers to the sdcard,

For the state of the external setting in the Android system, we should use the media_mounted (SDcard exists and can read and write) media_mounted_read_only (SDcard exists, can only read) Of course, there are other states that can be found in the document

5:getrootdirectory () get to the Android root path

6:isexternalstorageemulated () returns a Boolean value to determine whether the external setting is valid

7:isexternalstorageremovable () returns a Boolean value that determines whether external settings can be removed

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
android:layout_width=" fill_parent "
android:layout_height=" fill_parent "
android:o" rientation= "vertical" >
<textview
android:layout_width= "Fill_parent"
Wrap_content "
android:text=" @string/hello/>
<edittext android:id=
"@+id/et1"
android: Layout_width= "Fill_parent"
android:layout_height= "wrap_content"/> <button android:id=
"@+" Id/bt1 "
android:layout_width=" wrap_content "
android:layout_height=" wrap_content "
android:text=" Use SDcard write "/>
<edittext
android:id="
@+id/et2 "android:layout_width=" Fill_parent " android:layout_height= "Wrap_content"/>
<button
android:id= "@+id/bt2"
android:layout_width = "Wrap_content"
android:layout_height= "wrap_content"
android:text= "use sdcard read operation"/>

Package com.example.yanlei.yh;

Import Android.os.Bundle;
Import android.os.Environment;
Import android.support.v7.app.AppCompatActivity;
Import Android.view.Menu;
Import Android.view.MenuItem;
Import Android.widget.TextView;
Import Org.apache.http.util.EncodingUtils;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import java.util.ArrayList;
Import java.util.List;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import android.app.Activity;
Import Android.content.Context;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.Toast; public class Mainactivity extends Appcompatactivity {private Button bt1, bt2; private EditText et1, Et2; private static F Inal String FilenamE = "Temp_file.txt"; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_main);
BT1 = (Button) This.findviewbyid (R.ID.BT1);
BT2 = (Button) This.findviewbyid (R.ID.BT2);
Et1 = (edittext) This.findviewbyid (R.ID.ET1);
Et2 = (edittext) This.findviewbyid (R.id.et2);
Bt1.setonclicklistener (New Mysetonclicklistener ());
Bt2.setonclicklistener (New Mysetonclicklistener ()); Private class Mysetonclicklistener implements Onclicklistener {@Override public void OnClick (View v) {File File = new
File (Environment.getexternalstoragedirectory (), FILENAME); Switch (V.getid ()) {case r.id.bt1://use SDcard write operation if (Environment.getexternalstoragestate (). Equals (Environment.media_ Mounted)) {try {fileoutputstream fos = new FileOutputStream (file); Fos.write (Et1.gettext (). toString (). GetBytes ());
. Close ();
Toast.maketext (Mainactivity.this, "Write file succeeded", Toast.length_long). Show (); catch (Exception e) {toast.maketext (Mainactivity.this, "Write file failed ", Toast.length_short". Show (); } else {//This time sdcard does not exist or cannot read or write Toast.maketext (mainactivity.this, "sdcard does not exist or cannot read or write at this time", Toast.length_short).
Show ();
} break;
Case r.id.bt2://Use SDcard read operation if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {try {
FileInputStream InputStream = new FileInputStream (file);
Byte[] B = new byte[inputstream.available ()];
Inputstream.read (b);
Et2.settext (New String (b));
Toast.maketext (Mainactivity.this, "read the file successfully", Toast.length_long). Show (); catch (Exception e) {toast.maketext (Mainactivity.this, read failed, Toast.length_short). Show ();} else {//At this point, sdcard does not exist or cannot read or write Toast.maketext (mainactivity.this, "sdcard does not exist or cannot read or write," Toast.length_short). Show
();
} break; @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds the items to the action Bar if
It is present.
Getmenuinflater (). Inflate (R.menu.menu_main, menu);
return true; @Override public boolean onoptionsitemselected (MenuItem Item){///Handle Action Bar item clicks here. The action bar would//automatically handle clicks on the Home/up button, so long//as your specify a parent activity in a
ndroidmanifest.xml. int id = item.getitemid (); Noinspection simplifiableifstatement if (id = = r.id.action_settings) {return true;} return super.onoptionsitemselecte
D (item); }
}

The above described to you the use of Android SDcard read files, I hope to help!

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.