六、把文件存放在SDCard

时间:2022-10-05 12:43:49

使用Activity的openFileOutput()方法保存文件,文件是存放在手机空间上,一般手机的存储空间不是很大,存放些小文件还行,如果要存放像视频这样的大文件,是不可行的。对于像视频这样的大文件,我们可以把它存放在SDCard。 SDCard是干什么的?你可以把它看作是移动硬盘或U盘。

                 

在模拟器中使用SDCard,你需要先创建一张SDCard卡(当然不是真的SDCard,只是镜像文件)。创建SDCard可以在Eclipse创建模拟器时随同创建,也可以使用DOS命令进行创建,如下:在Dos窗口中进入android SDK安装路径的tools目录,输入以下命令创建一张容量为2G的SDCard,文件后缀可以随便取,建议使用.img:
mksdcard 2048M D:\AndroidTool\sdcard.img

                   

注意:在程序中访问SDCard,你需要申请访问SDCard的权限。
在AndroidManifest.xml中加入访问SDCard的权限如下:
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

          
要往SDCard存放文件,程序必须先判断手机是否装有SDCard,并且可以进行读写。
注意:访问SDCard必须在AndroidManifest.xml中加入访问SDCard的权限
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
         File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
         File saveFile = new File(sdCardDir, “ljq.txt”);
         FileOutputStream outStream = new FileOutputStream(saveFile);
         outStream.write("abc".getBytes());
         outStream.close();
}
Environment.getExternalStorageState()方法用于获取SDCard的状态,如果手机装有SDCard,并且可以进行读写,

那么方法返回的状态等于Environment.MEDIA_MOUNTED。
          

Environment.getExternalStorageDirectory()方法用于获取SDCard的目录,当然要获取SDCard的目录,你也可以这样写:
File sdCardDir = new File("/mnt/sdcard"); //获取SDCard目录
File saveFile = new File(sdCardDir, "ljq.txt");
//上面两句代码可以合成一句: File saveFile = new File("/mnt/sdcard/ljq.txt");
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("abc".getBytes());
outStream.close();

              

案例

main.xml布局文件

  
  
  
<? 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"
>
<!-- 相对布局 -->
< RelativeLayout xmlns:android ="http://schemas.android.com/apk/res/android"
android:orientation
="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"
android: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_width ="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" />
</ RelativeLayout >
< 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 " > 数据保存 </ string >
< string name = " filename " > 文件名称 </ string >
< string name = " content " > 文件内容 </ string >
< string name = " button " > 保存 </ string >
< string name = " readButton " > 读取内容 </ string >
< string name = " error " > 保存失败 </ string >
< string name = " success " > 保存成功 </ string >
</ resources >

            

FileService工具类

  
  
  
package com.ljq.service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileService {

/**
* 保存数据
*
*
@param outputStream
*
@param content
*
@throws Exception
*/
public static void save(OutputStream outputStream, String content) throws Exception {
outputStream.write(content.getBytes());
outputStream.close();
}

/**
* 读取数据
*
*
@param inputStream
*
@return
*
@throws Exception
*/
public static String read(InputStream inputStream) throws Exception {
ByteArrayOutputStream byteArrayOutputStream
= new ByteArrayOutputStream(); // 往内存写数据
byte [] buffer = new byte [ 1024 ]; // 缓冲区
int len = - 1 ;
while ((len = inputStream.read(buffer)) != - 1 ) {
byteArrayOutputStream.write(buffer,
0 , len);
}
byte [] data = byteArrayOutputStream.toByteArray(); // 存储数据
byteArrayOutputStream.close();
inputStream.close();
return new String(data);
}
}

              

SdcardActivity类

  
  
  
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()等价于new File("/sdcard")---->获取sdcard目录
// 获取sdcard目录
// File file = new File("/sdcard" + filename);
File file = new File(Environment.getExternalStorageDirectory(), filename);
switch (button.getId()) {
case R.id.button:
int resId = R.string.success; // 默认成功
String content = contentText.getText().toString();
// sdcard存在并且可以读写
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
FileOutputStream 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不存在或写保护 " , 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 , " 读取失败 " , Toast.LENGTH_LONG).show();
}
break ;
}
}

};
}

             

清单文件

  
  
  
<? 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" />
<!-- 在SDCard中创建与删除文件权限 -->
< uses-permission
android:name ="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 往SDCard写入数据权限 -->
< uses-permission android:name ="android.permission.WRITE_EXTERNAL_STORAGE" />

</ manifest >

              

运行结果

六、把文件存放在SDCard