Android - 文件讀寫操作 總結

http://blog.csdn.net/ztp800201/article/details/7322110


在android中的文件放在不同位置,它們的讀取方式也有一些不同。

本文對android中對資源文件的讀取、數據區文件的讀取、SD卡文件的讀取及RandomAccessFile的方式和方法進行了整理。供參考。


一、資源文件的讀取:

      1) 從resource的raw中讀取文件數據:

[java] view plaincopy
  1. String res = "";   
  2. try{   
  3.    
  4.     //得到資源中的Raw數據流  
  5.     InputStream in = getResources().openRawResource(R.raw.test);   
  6.   
  7.     //得到數據的大小  
  8.     int length = in.available();         
  9.   
  10.     byte [] buffer = new byte[length];          
  11.   
  12.     //讀取數據  
  13.     in.read(buffer);           
  14.   
  15.     //依test.txt的編碼類型選擇合適的編碼,如果不調整會亂碼   
  16.     res = EncodingUtils.getString(buffer, "BIG5");   
  17.       
  18.     //關閉      
  19.     in.close();              
  20.   
  21.    }catch(Exception e){   
  22.       e.printStackTrace();           
  23.    }   

 2) 從resource的asset中讀取文件數據

[java] view plaincopy
  1. String fileName = "test.txt"//文件名字   
  2. String res="";   
  3. try{   
  4.   
  5.    //得到資源中的asset數據流  
  6.    InputStream in = getResources().getAssets().open(fileName);   
  7.   
  8.    int length = in.available();           
  9.    byte [] buffer = new byte[length];          
  10.   
  11.    in.read(buffer);              
  12.    in.close();  
  13.    res = EncodingUtils.getString(buffer, "UTF-8");       
  14.   
  15.   }catch(Exception e){   
  16.   
  17.       e.printStackTrace();           
  18.   
  19.    }   


二、讀寫/data/data/<應用程序名>目錄上的文件:

[java] view plaincopy
  1. //寫數據  
  2. public void writeFile(String fileName,String writestr) throws IOException{   
  3.   try{   
  4.   
  5.         FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);   
  6.   
  7.         byte [] bytes = writestr.getBytes();   
  8.   
  9.         fout.write(bytes);   
  10.   
  11.         fout.close();   
  12.       }   
  13.   
  14.         catch(Exception e){   
  15.         e.printStackTrace();   
  16.        }   
  17. }   
  18.   
  19. //讀數據  
  20. public String readFile(String fileName) throws IOException{   
  21.   String res="";   
  22.   try{   
  23.          FileInputStream fin = openFileInput(fileName);   
  24.          int length = fin.available();   
  25.          byte [] buffer = new byte[length];   
  26.          fin.read(buffer);       
  27.          res = EncodingUtils.getString(buffer, "UTF-8");   
  28.          fin.close();       
  29.      }   
  30.      catch(Exception e){   
  31.          e.printStackTrace();   
  32.      }   
  33.      return res;   
  34.   
  35. }     

三、讀寫SD卡中的文件。也就是/mnt/sdcard/目錄下面的文件 :

[java] view plaincopy
  1. //寫數據到SD中的文件  
  2. public void writeFileSdcardFile(String fileName,String write_str) throws IOException{   
  3.  try{   
  4.   
  5.        FileOutputStream fout = new FileOutputStream(fileName);   
  6.        byte [] bytes = write_str.getBytes();   
  7.   
  8.        fout.write(bytes);   
  9.        fout.close();   
  10.      }  
  11.   
  12.       catch(Exception e){   
  13.         e.printStackTrace();   
  14.        }   
  15.    }   
  16.   
  17.     
  18. //讀SD中的文件  
  19. public String readFileSdcardFile(String fileName) throws IOException{   
  20.   String res="";   
  21.   try{   
  22.          FileInputStream fin = new FileInputStream(fileName);   
  23.   
  24.          int length = fin.available();   
  25.   
  26.          byte [] buffer = new byte[length];   
  27.          fin.read(buffer);       
  28.   
  29.          res = EncodingUtils.getString(buffer, "UTF-8");   
  30.   
  31.          fin.close();       
  32.         }   
  33.   
  34.         catch(Exception e){   
  35.          e.printStackTrace();   
  36.         }   
  37.         return res;   
  38. }   

四、使用File類進行文件的讀寫:

[java] view plaincopy
  1. //讀文件  
  2. public String readSDFile(String fileName) throws IOException {    
  3.   
  4.         File file = new File(fileName);    
  5.   
  6.         FileInputStream fis = new FileInputStream(file);    
  7.   
  8.         int length = fis.available();   
  9.   
  10.          byte [] buffer = new byte[length];   
  11.          fis.read(buffer);       
  12.   
  13.          res = EncodingUtils.getString(buffer, "UTF-8");   
  14.   
  15.          fis.close();       
  16.          return res;    
  17. }    
  18.   
  19. //寫文件  
  20. public void writeSDFile(String fileName, String write_str) throws IOException{    
  21.   
  22.         File file = new File(fileName);    
  23.   
  24.         FileOutputStream fos = new FileOutputStream(file);    
  25.   
  26.         byte [] bytes = write_str.getBytes();   
  27.   
  28.         fos.write(bytes);   
  29.   
  30.         fos.close();   
  31. }   

五、另外,File類還有下面一些常用的操作:

[java] view plaincopy
  1. String Name = File.getName();  //獲得文件或文件夾的名稱:  
  2. String parentPath = File.getParent();  //獲得文件或文件夾的父目錄  
  3. String path = File.getAbsoultePath();//絕對路經  
  4. String path = File.getPath();//相對路經   
  5. File.createNewFile();//建立文件    
  6. File.mkDir(); //建立文件夾    
  7. File.isDirectory(); //判斷是文件或文件夾  
  8. File[] files = File.listFiles();  //列出文件夾下的所有文件和文件夾名  
  9. File.renameTo(dest);  //修改文件夾和文件名  
  10. File.delete();  //刪除文件夾或文件  

六、使用RandomAccessFile進行文件的讀寫:

RandomAccessFile的使用方法比較靈活,功能也比較多,可以使用類似seek的方式可以跳轉到文件的任意位置,從文件指示器當前位置開始讀寫。
它有兩種構造方法
new RandomAccessFile(f,"rw");//讀寫方式
new RandomAccessFile(f,"r");//只讀方式
使用事例:

[java] view plaincopy
  1. /*  
  2.  * 程序功能:演示了RandomAccessFile類的操作,同時實現了一個文件複製操作。  
  3.  */    
  4.     
  5. import java.io.*;    
  6.     
  7. public class RandomAccessFileDemo {    
  8.  public static void main(String[] args) throws Exception {    
  9.   RandomAccessFile file = new RandomAccessFile("file""rw");    
  10.   // 以下向file文件中寫數據    
  11.   file.writeInt(20);// 佔4個字節    
  12.   file.writeDouble(8.236598);// 佔8個字節    
  13.   file.writeUTF("這是一個UTF字符串");// 這個長度寫在當前文件指針的前兩個字節處,可用readShort()讀取    
  14.   file.writeBoolean(true);// 佔1個字節    
  15.   file.writeShort(395);// 佔2個字節    
  16.   file.writeLong(2325451l);// 佔8個字節    
  17.   file.writeUTF("又是一個UTF字符串");    
  18.   file.writeFloat(35.5f);// 佔4個字節    
  19.   file.writeChar('a');// 佔2個字節    
  20.     
  21.   file.seek(0);// 把文件指針位置設置到文件起始處    
  22.     
  23.   // 以下從file文件中讀數據,要注意文件指針的位置    
  24.   System.out.println("——————從file文件指定位置讀數據——————");    
  25.   System.out.println(file.readInt());    
  26.   System.out.println(file.readDouble());    
  27.   System.out.println(file.readUTF());    
  28.     
  29.   file.skipBytes(3);// 將文件指針跳過3個字節,本例中即跳過了一個boolean值和short值。    
  30.   System.out.println(file.readLong());    
  31.     
  32.   file.skipBytes(file.readShort()); // 跳過文件中“又是一個UTF字符串”所佔字節,注意readShort()方法會移動文件指針,所以不用加2。    
  33.   System.out.println(file.readFloat());    
  34.       
  35.   //以下演示文件複製操作    
  36.   System.out.println("——————文件複製(從file到fileCopy)——————");    
  37.   file.seek(0);    
  38.   RandomAccessFile fileCopy=new RandomAccessFile("fileCopy","rw");    
  39.   int len=(int)file.length();//取得文件長度(字節數)    
  40.   byte[] b=new byte[len];    
  41.   file.readFully(b);    
  42.   fileCopy.write(b);    
  43.   System.out.println("複製完成!");    
  44.  }    
  45. }    


七、讀取資源文件時能否實現類似於seek的方式可以跳轉到文件的任意位置,從指定的位置開始讀取指定的字節數呢?

答案是可以的。

在FileInputStream和InputStream中都有下面的函數:

[java] view plaincopy
  1. public long skip (long byteCount); //從數據流中跳過n個字節  
  2. public int read (byte[] buffer, int offset, int length); //從數據流中讀取length數據存在buffer的offset開始的位置。offset是相對於buffer的開始位置的,不是數據流。  

可以使用這兩個函數來實現類似於seek的操作,請看下面的測試代碼:

[java] view plaincopy
  1. //其中read_raw是一個txt文件,存放在raw目錄下。  
  2. //read_raw.txt文件的內容是:"ABCDEFGHIJKLMNOPQRST"  
  3. public String getRawString() throws IOException {  
  4.       
  5.     String str = null;  
  6.       
  7.     InputStream in = getResources().openRawResource(R.raw.read_raw);  
  8.       
  9.     int length = in.available();  
  10.     byte[] buffer = new byte[length];  
  11.       
  12.     in.skip(2); //跳過兩個字節  
  13.     in.read(buffer,0,3); //讀三個字節  
  14.       
  15.     in.skip(3); //跳過三個字節  
  16.     in.read(buffer,0,3); //讀三個字節  
  17.       
  18.     //最後str="IJK"  
  19.     str = EncodingUtils.getString(buffer, "BIG5");  
  20.       
  21.       
  22.     in.close();  
  23.       
  24.     return str;  
  25. }  

從上面的實例可以看出skip函數有點類似於C語言中的seek操作,但它們之間有些不同。

需要注意的是:

1、skip函數始終是從當前位置開始跳的。在實際應用當中還要再判斷一下該函數的返回值。

2、read函數也始終是當前位置開始讀的。

3、另外,還可以使用reset函數將文件的當前位置重置爲0,也就是文件的開始位置。


如何得到文件的當前位置?

我沒有找到相關的函數和方法,不知道怎麼樣才能得到文件的當前位置,貌似它也並不是太重要。


八、如何從FileInputStream中得到InputStream?

[java] view plaincopy
  1. public String readFileData(String fileName) throws IOException{   
  2.   String res="";   
  3.   try{   
  4.          FileInputStream fin = new FileInputStream(fileName);   
  5.      InputStream in = new BufferedInputStream(fin);  
  6.   
  7.          ...  
  8.   
  9.       }  
  10.       catch(Exception e){   
  11.          e.printStackTrace();   
  12.       }  
  13.   
  14. }  

九、APK資源文件的大小不能超過1M,如果超過了怎麼辦?我們可以將這個數據再複製到data目錄下,然後再使用。複製數據的代碼如下:

[java] view plaincopy
  1. public boolean assetsCopyData(String strAssetsFilePath, String strDesFilePath){  
  2.        boolean bIsSuc = true;  
  3.        InputStream inputStream = null;  
  4.        OutputStream outputStream = null;  
  5.          
  6.        File file = new File(strDesFilePath);  
  7.        if (!file.exists()){  
  8.            try {  
  9.               file.createNewFile();  
  10.               Runtime.getRuntime().exec("chmod 766 " + file);  
  11.            } catch (IOException e) {  
  12.               bIsSuc = false;  
  13.            }  
  14.              
  15.        }else{//存在  
  16.            return true;  
  17.        }  
  18.          
  19.        try {  
  20.            inputStream = getAssets().open(strAssetsFilePath);  
  21.            outputStream = new FileOutputStream(file);  
  22.              
  23.            int nLen = 0 ;  
  24.              
  25.            byte[] buff = new byte[1024*1];  
  26.            while((nLen = inputStream.read(buff)) > 0){  
  27.               outputStream.write(buff, 0, nLen);  
  28.            }  
  29.              
  30.            //完成  
  31.        } catch (IOException e) {  
  32.            bIsSuc = false;  
  33.        }finally{  
  34.            try {  
  35.               if (outputStream != null){  
  36.                   outputStream.close();  
  37.               }  
  38.                 
  39.               if (inputStream != null){  
  40.                   inputStream.close();  
  41.               }  
  42.            } catch (IOException e) {  
  43.               bIsSuc = false;  
  44.            }  
  45.              
  46.        }  
  47.          
  48.        return bIsSuc;  
  49.     }     




轉載時請註明出處:http://blog.csdn.net/ztp800201/article/details/7322110


總結:

1、apk中有兩種資源文件,使用兩種不同的方式進行打開使用。
raw使用InputStream in = getResources().openRawResource(R.raw.test);
asset使用InputStream in = getResources().getAssets().open(fileName);

這些數據只能讀取,不能寫入。更重要的是該目錄下的文件大小不能超過1M。

同時,需要注意的是,在使用InputStream的時候需要在函數名稱後加上throws IOException。

2、SD卡中的文件使用FileInputStream和FileOutputStream進行文件的操作。
3、存放在數據區(/data/data/..)的文件只能使用openFileOutput和openFileInput進行操作。
注意不能使用FileInputStream和FileOutputStream進行文件的操作。
4、RandomAccessFile類僅限於文件的操作,不能訪問其他IO設備。它可以跳轉到文件的任意位置,從當前位置開始讀寫。

5、InputStream和FileInputStream都可以使用skip和read(buffre,offset,length)函數來實現文件的隨機讀取。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章