本篇博文实现android将字符串数据保存到SD卡上以及从SD读数据返回。上代码:
package com.example.android_file2;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.os.Environment;
public class FileService {
/**
* 保存内容到SDcard
*
* @param filename文件名称
* @param info文件内容
* @return
*/
public static String saveInfoToSDcard(String filename, String info) {
String result = "false";
File file = new File(Environment.getExternalStorageDirectory(),
filename);
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(info.getBytes());
result = "true";
fileOutputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println("Environment");
}
return result;
}
/**
* 读sd卡上的数据
* @param filename
* @return
*/
public static String getStringFromSdcard(String filename) {
String result = null;
// 缓存的流,和磁盘无关,不需要关闭
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
File file = new File(Environment.getExternalStorageDirectory(),
filename);
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
int len = 0;
byte[] buffer = new byte[1024];
while ((len = fileInputStream.read(buffer)) != -1) {
arrayOutputStream.write(buffer, 0, len);
}
fileInputStream.close();
result = new String(arrayOutputStream.toByteArray());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
}
上面类中的方法分别实现SD卡上存取数据。
还需要在AndroidMainfest.xml中添加使用权限: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
这样就可以实现向SD卡上存取数据了。