标签:
安卓文件存储分为内存存储和SD卡存储:
1)存储在SD卡中与写文件到内存:
一般我们想要在SD卡中存数据或读数据我们首先需要判断SD卡是否存在: Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
然后是存储SD卡中我们要用的是FileOutputStream而不能是openFileOutput该方法是提供给写文件到内存中使用的,且使用openFileOutput时文件路径不能有分割符;
/**
* 写文件到SD卡注意现在高版本的api不支持自动创建文件了所以一定要自己创建不然会报错
*/
public File writeFileToSD(String content){
if(!hasSD) return null;
File fileP = new File(PATHNAME);
File file = new File(PATHNAME + TxtName);
if(!fileP.exists()){
fileP.mkdirs();
}
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream out = new FileOutputStream(file);
Writer writer = new OutputStreamWriter(out);
writer.write(content);
writer.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return file;
}
/**
* 写文件到内存使用openFileOutput方法且内存地址不能有分割符
* @param context
* TxtName是我自定义的一个文件名可以是test.txt
* @param content 需要写入的内容
*/
public void WriteFile(Context context ,String content){
int len = 0;
byte[] buffer = content.getBytes();
len = buffer.length;
FileOutputStream out = null;
try {
out = context.openFileOutput(TxtName, Context.MODE_PRIVATE);
out.write(buffer,0 ,len);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2)文件的读取:
同样的我们在读取文件的时候,读取SD卡中的数据我们要用到的是FileInputStream方法而不能是openFileInput该反法是由context提供的读取内存中的文件的
/**
* 读取SD卡中文本文件
* @return
*/
public String readSDFile() {
StringBuffer sb = new StringBuffer();
File file = new File(PATHNAME + TxtName);
if (!file.exists()) {
return "";
}
try {
FileInputStream fis = new FileInputStream(file);
int c;
while ((c = fis.read()) != -1) {
sb.append((char) c);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
/**
*读存储在(内存)上的文件采用openFileInput的方法
*/
public String ReadFile(Context context)
{
String content = null;
FileInputStream read = null;
try {
read = context.openFileInput(TxtName);
} catch (FileNotFoundException e) {
return "";
}
/*byte[] txt = new byte[0];
try {
txt = new byte[read.available()];
read.read(txt);
} catch (IOException e) {
e.printStackTrace();
}
content = new String(txt);
T.showLog("======",content);*/
//创建一个内存输出流对象
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
try {
while((len = read.read(buffer)) != -1){
outstream.write(buffer, 0, len);
}
content = new String(outstream.toByteArray());
Log.i("content", content);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return content;
}
标签:
原文地址:http://www.cnblogs.com/zhangyp-pipi/p/5872608.html