安卓文件存储分为内存存储和SD卡存储:api
1)存储在SD卡中与写文件到内存:app
通常咱们想要在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;}