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;
}
Android之sdcard写入数据(源代码分享),布布扣,bubuko.com
Android之sdcard写入数据(源代码分享)