安卓的文件存儲(chǔ)讀寫主要有兩種:
1、data/data/包名/files 目錄下存儲(chǔ)节芥。
這種存儲(chǔ)是將文件存到手機(jī)內(nèi)存中對應(yīng)的包名下。軟件卸載后,存在這里的文件也全部被系統(tǒng)刪除头镊。此外蚣驼,存在這里的文件可定義訪問權(quán)限:
2、SD卡下存儲(chǔ)相艇。
常用于一些媒體文件颖杏,如圖片、音視頻坛芽、大文件等留储。
使用示例:
1、讀寫包名下文件
public class FileHelp {
private Context context;
public FileHelp(Context context) {
this.context = context;
}
public void fileWrite(String fileName, String fileContent) {
try {
FileOutputStream fos = context.openFileOutput(fileName,
MODE_PRIVATE);
fos.write(fileContent.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String fileRead(String fileName) {
try {
FileInputStream fis = context.openFileInput(fileName);
StringBuffer sb = new StringBuffer();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
sb.append(new String(buffer, 0, len));
}
fis.close();
return sb.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
2咙轩、SD卡讀寫
public class SDFileHelper {
public void fileWrite(String fileName, String content) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
try {
fileName = Environment.getExternalStorageDirectory()
.getCanonicalPath() + "/" + fileName;
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String fileRead(String fileName) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
fileName = Environment.getExternalStorageDirectory() + "/"
+ fileName;
try {
FileInputStream fis = new FileInputStream(fileName);
StringBuffer sb = new StringBuffer();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
sb.append(new String(buffer, 0, len));
}
fis.close();
return sb.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
這兩種方式基本差不多获讳,區(qū)別在于方式1是openFileInput/openFileOutput,方式2是直接new一個(gè)文件流臭墨。另外赔嚎,方式2需要先判斷SD卡是否掛載,然后獲取SD卡根目錄胧弛。