您的位置:首页 > 移动开发 > Android开发

Android开发之sdcard读写数据(源代码分享)

2014-03-21 12:46 387 查看
package com.example.f01_sdcard01;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;

public class FileUtiles {
// 在向sd卡写入数据时要记得向mainifest清单中增加一个 <uses-permission
// android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
// 传递两个参数,一个为文件名,一个为写入的数据
public void fileSave(String fileName, byte[] data) {

FileOutputStream fileOutputStream = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// 创建sdcard目录
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/txt");
// 如果目录不存在,就创建一个文件
if (!file.exists()) {
file.mkdirs();
}
try {
// 将数据写入指定文件中
fileOutputStream = new FileOutputStream(
new File(file, fileName));
try {
fileOutputStream.write(data, 0, data.length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

}

}public String readSdcard(String fileName){
//读取指定文件的数据
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/txt/");
// 如果目录不存在,就创建一个文件
if (file.exists()) {
File file2=new File(file, fileName);
InputStream inputStream=null;
ByteArrayOutputStream arrayOutputStream=new ByteArrayOutputStream();
try {
inputStream = new FileInputStream(file2);
byte[] data=new byte[1024];
int len=0;
try {
while((len=inputStream.read(data))!=-1){
arrayOutputStream.write(data, 0, len);
}
return new String(arrayOutputStream.toByteArray()); 
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

}

return null;

}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐