Android implements the method of storing files in SDcard _android

Source: Internet
Author: User
Tags file permissions

The example in this article describes how the Android implementation puts files in SDcard. Share to everyone for your reference. Specifically as follows:

Use the activity of the Openfileoutput () method to save the file, the file is stored in the mobile phone space, the general mobile phone storage space is not very large, storing small files also line, if you want to store such large files as video, it is not feasible. For large files like video, we can store them in SDcard. What's sdcard for? You can think of it as a removable hard disk or a USB drive.

To use SDcard in the emulator, you need to create a SDcard card (not really sdcard, just a mirrored file). Creating SDcard can be created with Eclipse creation simulator, or it can be created using DOS commands, as follows: Enter the tools directory of the Android SDK installation path in the DOS window, and enter the following command to create a sdcard with a capacity of 2G File suffix can be arbitrarily taken, recommended. IMG:

Mksdcard 2048M D:\AndroidTool\sdcard.img
Note: To access SDcard in your program, you need to apply for access to SDcard permissions.
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"/>

To store files to SDcard, the program must first determine whether the phone is fitted with sdcard and can read and write.
Note: Access to SDcard must be included in Androidmanifest.xml to access SDcard permissions

if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {
  File Sdcarddir = Environment.getexternalstoragedirectory ()//Get SDcard directory
  file SaveFile = new file (Sdcarddir, "ljq.txt");
  FileOutputStream OutStream = new FileOutputStream (savefile);
  Outstream.write ("abc". getBytes ());
  Outstream.close ();
}

The Environment.getexternalstoragestate () method is used to obtain the state of the sdcard, if the phone is fitted with sdcard and can be read and written,
The state returned by the method is equal to environment.media_mounted.
Environment.getexternalstoragedirectory () method is used to get the directory of SDcard, of course, to obtain the SDcard directory, you can also write:
File Sdcarddir = new file ("/mnt/sdcard"); Get SDcard Directory
File SaveFile = new file (Sdcarddir, "ljq.txt");
The above two code can synthesize one sentence: file SaveFile = new file ("/mnt/sdcard/ljq.txt");
FileOutputStream OutStream = new FileOutputStream (savefile);
Outstream.write ("abc". getBytes ());
Outstream.close ();

Case

Main.xml Layout file:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/"
 Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " > <!--relative layout--> <relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android" Android:o rientation= "vertical" android:layout_width= "fill_parent" android:layout_height= "wrap_content" > <TextView Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/filename" Android: Id= "@+id/filenamelable"/> <edittext android:layout_width= "250px" android:layout_height= "Wrap_content" Androi d:layout_torightof= "@id/filenamelable" android:layout_aligntop= "@id/filenamelable" android:layout_marginleft= " 10px "android:text=" Ljq.txt "android:id=" @+id/filename "/> </RelativeLayout> <textview Android:layout_wi Dth= "Fill_parent" android:layout_height= "Wrap_content" Android: text= "@string/content"/> <edittext android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:minlines= "3" android:id= "@+id/content"/> <relativelayout xmlns:android= "http://schemas.android.com/ Apk/res/android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Wrap_ Content "> <button android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:text=" @ String/button "android:id=" @+id/button "/> <button android:layout_width=" Wrap_content "android:layout_height= "Wrap_content" android:layout_torightof= "@id/button" android:layout_aligntop= "@id/button" Android:layout_ marginleft= "10px" android:minlines= "3" android:text= "@string/readbutton" android:id= "@+id/readbutton"/> </Re lativelayout> <textview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:id=

 "@+id/resultview"/> </LinearLayout>

Strings.xml:

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
 <string name= "Hello" >hello world, fileactivity!</string>
 <string name= "app_name" > Data save </string>
 <string name= "filename "> File name </string>
 <string name=" Content "> File content </string>
 <string name=" button "> Save </string>
 <string name= "Readbutton" > Read content </string>
 <string name= "error" > Save failed </ string>
 <string name= "Success" > Save success </string>
</resources>

Fileservice Tool Class:

 package com.ljq.service; import java.io.ByteArrayOutputStream; import
Java.io.InputStream;
Import Java.io.OutputStream; public class Fileservice {/** * Save data * * @param outputstream * @param content * @throws Exception/Public stat
 IC void Save (OutputStream outputstream, String content) throws Exception {outputstream.write ());
 Outputstream.close (); /** * Read Data * * @param inputstream * @return * @throws Exception/public static String read (InputStream inputs Tream) throws Exception {Bytearrayoutputstream Bytearrayoutputstream = new Bytearrayoutputstream ();//write data to memory byte[] Bu Ffer = new byte[1024];
 buffer int len =-1;
 while (len = inputstream.read (buffer))!=-1) {bytearrayoutputstream.write (buffer, 0, Len); } byte[] data = Bytearrayoutputstream.tobytearray ();
 Storage data bytearrayoutputstream.close ();
 Inputstream.close ();
 return new String (data); }
}

Sdcardactivity class:

Package Com.ljq.sdcard;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
Import android.app.Activity;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.TextView;
Import Android.widget.Toast;
Import Com.ljq.service.FileService;
 public class Sdcardactivity extends activity {Private final String TAG = "fileactivity";
 Private EditText Filenametext;
 Private TextView Resultview;
 Private EditText ContentText;
 @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.main);
 Filenametext = (edittext) This.findviewbyid (r.id.filename);
 ContentText = (edittext) This.findviewbyid (r.id.content);
 Resultview = (TextView) This.findviewbyid (R.id.resultview);
 Button button = (button) This.findviewbyid (R.id.button); Button.setonclIcklistener (listener);
 Button Readbutton = (button) This.findviewbyid (R.id.readbutton);
 Readbutton.setonclicklistener (listener); Private View.onclicklistener listener = new View.onclicklistener () {public void OnClick (View v) {button Button = (
  Button) v;
  String filename = Filenametext.gettext (). toString (); Environment.getexternalstoragedirectory () is equivalent to new File ("/sdcard")----> Get SDcard directory//Get SDcard directory//file File = new Fi
  Le ("/sdcard" + filename);
  File File = new file (environment.getexternalstoragedirectory (), filename); Switch (Button.getid ()) {case R.id.button:int resid = r.string.success;//default success String content = Contenttext.gette
  XT (). toString (); SDcard exists and can read/write if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {try {fileoutputst
   Ream FileOutputStream = new FileOutputStream (file);
   Fileservice.save (FileOutputStream, content);
   catch (Exception e) {log.e (TAG, e.tostring ());
   Resid = R.string.error;
 }  Toast.maketext (Sdcardactivity.this, Resid, Toast.length_long). Show ();
  }else {toast.maketext (sdcardactivity.this, "sdcard does not exist or write protection", Toast.length_long). Show ();
  } break;
   Case R.id.readbutton:try {inputstream inputstream= new FileInputStream (file);
   String Text = Fileservice.read (InputStream);
   Resultview.settext (text);
   catch (Exception e) {log.e (TAG, e.tostring ());
   Toast.maketext (Sdcardactivity.this, read failed, Toast.length_long). Show ();
  } break;
}
 }
 };

 }

Manifest file:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android=
"http://schemas.android.com/apk/res/" Android "
 package=" Com.ljq.sdcard "android:versioncode=" 1 "
 android:versionname=" 1.0 ">
 < Application android:icon= "@drawable/icon"
 android:label= "@string/app_name" >
 <activity android:name =". Sdcardactivity "
  android:label=" @string/app_name ">
  <intent-filter>
  <action android:name= "Android.intent.action.MAIN"/>
  <category
   android:name= "Android.intent.category.LAUNCHER"/>
  </intent-filter>
 </activity>
 </application>
 <uses-sdk android: minsdkversion= "7"/>
 <!--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"/>
</manifest>

Run Result:

I hope this article will help you with your 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.