android文件的讀寫主要分爲兩個方面,一個是將內容寫入本應用的data文件夾中,另一個是將內容寫入到sdcard中。兩者都使用I/O流的讀寫技術。
下面具體具體介紹這兩方面的內容:
一。將內容寫入本應用中:
/**
* @description:將內容保存到內置存儲中
* @author:Administrator
* @return:boolean
* @param fileName
* 文件名
* @param fileContent
* 文件內容
* @param context
* 上下文對象
* @return
*/
public static boolean fileSaveApp(String fileName, String fileContent,
Context context) {
try {
// 用android提供的輸出流來將內容寫入到文件中,注意mode的用途
FileOutputStream fos = context.openFileOutput(fileName,
context.MODE_APPEND);
fos.write(fileContent.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
注意android的上下文對象context在這個方法中起的的作用(可以用它來打開一個輸出流,或者打開一個輸入流),還有文件的寫入模式。這裏用的是文件的追加模式。數據時只可被本應用操作的。
二。將數據寫入sdcard中
/**
* @description:將內容寫入到sdcard的文件當中
* @author:Administrator
* @return:boolean
* @param fileName
* 文件名
* @param fileContent
* 文件內容
* @param path
* 文件路徑
* @return
*/
public static boolean fileSave(String fileName, String fileContent,
File path) {
File file = new File(path, fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fos = null;
int count = 0;
try {
fos = new FileOutputStream(file);
count = fileContent.getBytes().length;
fos.write(fileContent.getBytes(), 0, count);
fos.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
注意這個方法中的path參數指的是sdcard的路徑:=Environment.getExternalStorageDirectory();
注意寫入數據的時候需要判斷sdcard是否存在是否可寫:Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
最後需要注意如果要向sdcard寫入數據必須在manifest.xml加入權限: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />第一個權限是指對sdcard可寫,第二個權限是指可以在sdcard中建立和刪除文件。
最後將從應用的data中讀取數據的方法也寫進來:
/**
* @description:讀取本應用data文件夾中文件的內容(如果要讀取sdcard中的文件時一定要去判斷sdcard是否存在,並且是可讀的)
* @author:Administrator
* @return:String 文件的內容
* @param fileName
* 文件名
* @param context
* 上下文對象
* @return
*/
public static String readFile(String fileName, Context context) {
String str = "";
try {
FileInputStream fis = context.openFileInput(fileName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
// 用字節輸出流將讀到的內容寫入到內存中
bos.write(buffer, 0, len);
}
// 將輸出流中的數據轉換爲String
str = new String(bos.toByteArray(), "utf-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
這裏就不再介紹從sdcard中讀取文件內容的方法了。
這裏將android本應用的文件存儲的4中方式列舉出來:可以參考 http://www.cnblogs.com/jqyp/archive/2010/09/13/1825249.html