今天Leo要給大家總結一些關于Android文件讀寫的操作,在大家遇到關于這方面的問題,就不用東拼西湊的百度來百度去的,好了,話不多說,切入正題。
一、概要
apk中有兩種資源文件,raw下的和assert下的,這些數據只能讀取,不能寫入。更重要的是該目錄下的文件大小不能超過1M。
SD卡中的文件使用FileInputStream和FileOutputStream進行文件的操作。
存放在數據區(/data/data/..)的文件只能使用openFileOutput和openFileInput進行操作。注意這里不能使用FileInputStream和FileOutputStream進行文件的操作。
二、讀寫方式
資源文件(只讀)兩種資源文件,使用兩種不同的方式進行打開使用。
raw使用InputStream in = getResources().openRawResource(R.raw.test);
asset使用InputStream in = getResources().getAssets().open(fileName);
注:在使用InputStream的時候需要在函數名稱后加上throws IOException。數據區文件(/data/data/<應用程序名>目錄上的文件)
(1)寫操作:
FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);
(2)讀操作:FileInputStream fin = openFileInput(fileName);
(3)寫操作中的使用模式:
MODE_APPEND:即向文件尾寫入數據
MODE_PRIVATE:即僅打開文件可寫入數據
MODE_WORLD_READABLE:所有程序均可讀該文件數據
MODE_WORLD_WRITABLE:即所有程序均可寫入數據。-
sdcard數據
(1)讀操作
FileInputStream fin = new FileInputStream(fileName);
(2)寫操作
FileOutputStream fout = new FileOutputStream(fileName);
(3)必要步驟
①獲取權限
A 獲取文件創建修改權限
Paste_Image.png
B 可寫
Paste_Image.png
②檢查內存狀態(是否安裝sd卡)
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
③讀寫操作
關于sdcard
注意:訪問SDCard必須在AndroidManifest.xml中加入訪問SDCard的權限
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCardDir = Environment.getExternalStorageDirectory();//獲取SDCard目錄
File saveFile = new File(sdCardDir, “a.txt”);
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write(“test”.getBytes());
outStream.close();
}
Environment.getExternalStorageState()方法用于獲取SDCard的狀態,如果手機裝有SDCard,并且可以進行讀寫,那么方法返回的狀態等于Environment.MEDIA_MOUNTED。
Environment.getExternalStorageDirectory()方法用于獲取SDCard的目錄,當然要獲取SDCard的目錄,你也可以這樣寫:
File sdCardDir = new File(“/sdcard”); //獲取SDCard目錄
File saveFile = new File(sdCardDir, “itcast.txt”);
上面兩句代碼可以合成一句:
File saveFile = new File(“/sdcard/a.txt”);
FileInputStream是InputStream的子類
三、文件讀寫代碼示例
⒈ 資源文件的讀取:
① 從resource的raw中讀取文件數據:
String res = "";
try{
//得到資源中的Raw數據流
InputStream in = getResources().openRawResource(R.raw.test);
//得到數據的大小
int length = in.available();
byte [] buffer = new byte[length];
//讀取數據
in.read(buffer);
//依test.txt的編碼類型選擇合適的編碼,如果不調整會亂碼
res = EncodingUtils.getString(buffer, "BIG5");
//關閉
in.close();
}catch(Exception e){
e.printStackTrace();
}
② 從resource的asset中讀取文件數據:
String fileName = "test.txt"; //文件名字
String res="";
try{
//得到資源中的asset數據流
InputStream in = getResources().getAssets().open(fileName);
int length = in.available();
byte [] buffer = new byte[length];
in.read(buffer);
in.close();
res = EncodingUtils.getString(buffer, "UTF-8");
}catch(Exception e){
e.printStackTrace();
}
2. 讀寫/data/data/<應用程序名>目錄上的文件:
//寫數據
public void writeFile(String fileName,String writestr) throws IOException{
try{
FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);
byte [] bytes = writestr.getBytes();
fout.write(bytes);
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
//讀數據
public String readFile(String fileName) throws IOException{
String res="";
try{
FileInputStream fin = openFileInput(fileName);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}
catch(Exception e){
e.printStackTrace();
}
return res;
}
3.讀寫SD卡中的文件(也就是/mnt/sdcard/目錄下面的文件):
//寫數據到SD中的文件
public void writeFileSdcardFile(String fileName,String write_str) throws IOException{
try{
FileOutputStream fout = new FileOutputStream(fileName);
byte [] bytes = write_str.getBytes();
fout.write(bytes);
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
//讀SD中的文件
public String readFileSdcardFile(String fileName) throws IOException{
String res="";
try{
FileInputStream fin = new FileInputStream(fileName);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}
catch(Exception e){
e.printStackTrace();
}
return res;
}
4. 使用File類進行文件的讀寫:
//讀文件
public String readSDFile(String fileName) throws IOException {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
int length = fis.available();
byte [] buffer = new byte[length];
fis.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fis.close();
return res;
}
//寫文件
public void writeSDFile(String fileName, String write_str) throws IOException{
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
byte [] bytes = write_str.getBytes();
fos.write(bytes);
fos.close();
}
5. 另外,File類還有下面一些常用的操作:
String Name = File.getName(); //獲得文件或文件夾的名稱:
String parentPath = File.getParent(); //獲得文件或文件夾的父目錄
String path = File.getAbsoultePath();//絕對路經
String path = File.getPath();//相對路經
File.createNewFile();//建立文件
File.mkDir(); //建立文件夾
File.isDirectory(); //判斷是文件或文件夾
File[] files = File.listFiles(); //列出文件夾下的所有文件和文件夾名
File.renameTo(dest); //修改文件夾和文件名
File.delete(); //刪除文件夾或文件
6. 如何從FileInputStream中得到InputStream?
public String readFileData(String fileName) throws IOException{
String res="";
try{
FileInputStream fin = new FileInputStream(fileName);
InputStream in = new BufferedInputStream(fin);
...
}
catch(Exception e){
e.printStackTrace();
}
}
7. APK資源文件的大小不能超過1M,如果超過了怎么辦?
我們可以將這個數據再復制到data目錄下,然后再使用。復制數據的代碼如下:
public boolean assetsCopyData(String strAssetsFilePath, String strDesFilePath){
boolean bIsSuc = true;
InputStream inputStream = null;
OutputStream outputStream = null;
File file = new File(strDesFilePath);
if (!file.exists()){
try {
file.createNewFile();
Runtime.getRuntime().exec("chmod 766 " + file);
} catch (IOException e) {
bIsSuc = false;
}
}else{//存在
return true;
}
try {
inputStream = getAssets().open(strAssetsFilePath);
outputStream = new FileOutputStream(file);
int nLen = 0 ;
byte[] buff = new byte[1024*1];
while((nLen = inputStream.read(buff)) > 0){
outputStream.write(buff, 0, nLen);
}
//完成
} catch (IOException e) {
bIsSuc = false;
}finally{
try {
if (outputStream != null){
outputStream.close();
}
if (inputStream != null){
inputStream.close();
}
} catch (IOException e) {
bIsSuc = false;
}
}
return bIsSuc;
}
[詳細參考] (http://blog.csdn.net/ztp800201/article/details/7322110)
對于Android文件讀寫,leo就給大家介紹到這了,如有什么補充建議的地方,歡迎提出指正,喜歡的話,就點個贊吧……