实验_DataSaveSdcard

来源:互联网 发布:瑜伽软件下载 编辑:程序博客网 时间:2024/06/07 07:06

在Sd卡中新建chen文件夹前后:

新建FileService.java的代码:

package cn.example.cx9_6_datasavesdcard;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import android.os.Environment;public class FileService{public boolean saveFileToSdcard(String filename, byte[] data) throws IOException{String state = Environment.getExternalStorageState(); // 判断sdcard的状态FileOutputStream outputStream = null; // 表示sdcard卡挂在手机上 并且可以读写File root = Environment.getExternalStorageDirectory(); // 获得sdcard的根目录if (state.equals(Environment.MEDIA_MOUNTED)){File file = new File(root, filename);try{outputStream = new FileOutputStream(file);outputStream.write(data, 0, data.length);} catch (FileNotFoundException e){e.printStackTrace();} finally{if (outputStream != null){try{outputStream.close();} catch (IOException e){e.printStackTrace();}}}}return false;}}

Mainactivity.java的代码不需改变;

新建测试类Mytext.java的代码:

package cn.example.cx9_6_datasavesdcard;import java.io.IOException;import android.test.AndroidTestCase;public class Mytext extends AndroidTestCase{public void save() throws IOException{FileService service = new FileService();service.saveFileToSdcard("chen.text", "nihaoaniazainalia".getBytes());}}
选中save()右击选择测试。

0 0
原创粉丝点击