文件的存儲和讀取

安卓文件存儲分爲內存存儲和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;}
相關文章
相關標籤/搜索