Read and Write Android SD card files

Source: Internet
Author: User

The SD card uses a fat (File Allocation Table) file system and does not support access mode and permission control. The SD card is suitable for storing large-sized files or files without the need to set access permissions.
Android simulators support SD card, but the simulator does not have the default SD card. Developers must manually add the SD card image file to the simulator.
To read/write SD card files, you must add the read/write SD card permission to androidmanifest. xml.
Permission to create and delete files on the SD card
Android. Permission. mount_unmount_policesystems
Permission to write data to SD card
Android. Permission. write_external_storage

Method 1
First, check whether the/mnt/sdcard directory of the system is available.
Use an input/output stream of a file to read and write files in the SD card.
Method 2
Call the getexternalstoragestate () method of environment to determine whether the mobile phone has an SD card and the application has the permission to read and write the SD card.
Environment. getexternalstoragestate (). Equals (environment. media_mounted)
Call the getexternalstoragedirectory () method of environment to obtain the external memory, that is, the root directory of the SD card.
Use the input and output streams of files to read and write files in the SD card.

Core code

Write File to SD card
// If the mobile phone is inserted with an SD card and the application has the permission to access the SD card
If (environment. getexternalstoragestate ()
. Equals (environment. media_mounted ))
{
// Obtain the directory of the SD card
File sdcarddir = environment. getexternalstoragedirectory ();
File targetfile = new file (sdcarddir. GetCanonicalPath () + file_name );
// Create with specified file
Randomaccessfile object. The first parameter is the file name, and the second parameter is the read/write mode.
Randomaccessfile RAF = new randomaccessfile (targetfile, "RW ");
// Move the file record pointer to the end
Raf. Seek (targetfile. Length ());
// Output file content
Raf. Write (content. getbytes ());
Raf. Close ();
}

Read SD card files
// If the mobile phone is inserted with an SD card and the application has the permission to access the SD card
If (environment. getexternalstoragestate ()
. Equals (environment. media_mounted ))
{
// Obtain the storage directory corresponding to the SD card
File sdcarddir = environment. getexternalstoragedirectory ();
// Obtain the input stream corresponding to the specified file
Fileinputstream FCM = new fileinputstream (sdcarddir. GetCanonicalPath () + file_name );
// Package the specified input stream into bufferedreader
Bufferedreader BR = new bufferedreader (New inputstreamreader (FCM ));
Stringbuilder sb = new stringbuilder ("");
String line = NULL;
// Read until the last hop
While (line = Br. Readline ())! = NULL)
{
// Append read content
SB. append (line );
}
// Return the read content and convert it to a string
Return sb. tostring ();
}

Note: you must add permissions.
<! -- Create and delete a file on the SD card -->
<Uses-Permission Android: Name = "android. Permission. mount_unmount_filesystems"/>
<! -- Write data permission to SD card -->
<Uses-Permission Android: Name = "android. Permission. write_external_storage"/>

The following example shows how to write the edittext content to the SD card by pressing the write button. Then, you can read the files in the SD card by pressing the read button.

The first step is to compile the main. xml file.

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 <EditText android:id="@+id/edit1"
7 android:layout_width="fill_parent"
8 android:layout_height="wrap_content"
9 android:lines="4"/>
10 <Button android:id="@+id/write"
11 android:layout_width="wrap_content"
12 android:layout_height="wrap_content"
13 android:text="@string/write"/>
14 <EditText android:id="@+id/edit2"
15 android:layout_width="fill_parent"
16 android:layout_height="wrap_content"
17 android:editable="false"
18 android:cursorVisible="false"
19 android:lines="4"/>
20 <Button android:id="@+id/read"
21 android:layout_width="wrap_content"
22 android:layout_height="wrap_content"
23 android:text="@string/read"/>
24 </LinearLayout>

Step 2: Write the core code:

View code

1 package cn.edu. zwu. Tel;
2
3 Import java. Io. bufferedreader;
4 Import java. Io. file;
5 import java. Io. fileinputstream;
6 Import java. Io. inputstreamreader;
7 Import java. Io. randomaccessfile;
8 Import Android. App. activity;
9 Import Android. OS. Bundle;
10 Import Android. OS. environment;
11 import Android. View. view;
12 Import Android. View. View. onclicklistener;
13 Import Android. widget. Button;
14 Import Android. widget. edittext;
15 Import Android. OS. Bundle;
16
17 public class filesdsavetest02activity extends Activity
18 {
19 final string file_name = "/filesdtest. ini ";
20
21 @ override
22 public void oncreate (bundle savedinstancestate)
23 {
24 super. oncreate (savedinstancestate );
25 setcontentview (R. layout. Main );
26 // get two buttons
27 button READ = (button) findviewbyid (R. Id. Read );
28 button write = (button) findviewbyid (R. Id. Write );
29 // get two text boxes
30 final edittext edit1 = (edittext) findviewbyid (R. Id. edit1 );
31 Final edittext edit2 = (edittext) findviewbyid (R. Id. edit2 );
32 // bind the event listener to the write button
33 write. setonclicklistener (New onclicklistener ()
34 {
35 @ override
36 Public void onclick (View Source)
37 {
38 // write the content in edit1 to the file
39 write (edit1.gettext (). tostring ());
40 edit1.settext ("");
41}
42 });
43
44 read. setonclicklistener (New onclicklistener ()
45 {
46 @ override
47 Public void onclick (view V)
48 {
49 // read and display the content in the specified file
50 edit2.settext (read ());
51}
52 });
53}
54
55 private string read ()
56 {
57 try
58 {
59 // If the mobile phone is inserted with an SD card and the app has the permission to access the SD card
60 if (environment. getexternalstoragestate ()
61. Equals (environment. media_mounted ))
62 {
63 // obtain the storage directory corresponding to the SD card
64 file sdcarddir = environment. getexternalstoragedirectory ();
65 // obtain the input stream corresponding to the specified file
66 fileinputstream FCM = new fileinputstream (sdcarddir
67. GetCanonicalPath () + file_name );
68 // package the specified input stream into bufferedreader
69 bufferedreader BR = new bufferedreader (New
70 inputstreamreader (FCM ));
71 stringbuilder sb = new stringbuilder ("");
72 string line = NULL;
73 while (line = Br. Readline ())! = NULL)
74 {
75 sb. append (line );
76}
77 return sb. tostring ();
78}
79}
80 catch (exception E)
81 {
82 E. printstacktrace ();
83}
84 return NULL;
85}
86
87 private void write (string content)
88 {
89 try
90 {
91 // If the mobile phone is inserted with an SD card and the app has permission to access the SD card
92 If (environment. getexternalstoragestate ()
93. Equals (environment. media_mounted ))
94 {
95 // get the directory of the SD card
96 file sdcarddir = environment. getexternalstoragedirectory ();
97 file targetfile = new file (sdcarddir. GetCanonicalPath ()
98 + file_name );
99 // create a randomaccessfile object with the specified file. The first parameter is the file name, and the second parameter is the read/write mode.
100 randomaccessfile RAF = new randomaccessfile (
101 targetfile, & quot; RW & quot ");
102 // move the file record pointer to the end
103 Raf. Seek (targetfile. Length ());
104 // output file content
105 Raf. Write (content. getbytes ());
106 Raf. Close ();
107}
108}
109 catch (exception E)
110 {
111 E. printstacktrace ();
112}
113}
114}

Step 3: Modify the androidmainfest file to add permissions.

View code

1 <? XML version = "1.0" encoding = "UTF-8"?>
2 <manifest xmlns: Android = "http://schemas.android.com/apk/res/android"
3 package = "cn.edu. zwu. tel"
4 Android: versioncode = "1"
5 Android: versionname = "1.0" type = "codeph" text = "/codeph">
6
7 <uses-SDK Android: minsdkversion = "8"/>
8
9 <Application
10 Android: icon = "@ drawable/ic_launcher"
11 Android: Label = "@ string/app_name">
12 <Activity
13 Android: Name = ". filesdsavetest02activity"
14 Android: Label = "@ string/app_name">
15 <intent-filter>
16 <action Android: Name = "android. Intent. Action. Main"/>
17
18 <category Android: Name = "android. Intent. Category. launcher"/>
19 </intent-filter>
20 </activity>
21 </Application>
22 <! -- Create and delete a file on the SD card -->
23 <uses-Permission Android: Name = "android. Permission. mount_unmount_filesystems"/>
24 <! -- Write data permission to SD card -->
25 <uses-Permission Android: Name = "android. Permission. write_external_storage"/>
26 </manifest>

:

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.