生活随笔
收集整理的這篇文章主要介紹了
Android - 文件读写操作 总结
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
http://blog.csdn.net/ztp800201/article/details/7322110
在android中的文件放在不同位置,它們的讀取方式也有一些不同。
本文對android中對資源文件的讀取、數(shù)據(jù)區(qū)文件的讀取、SD卡文件的讀取及RandomAccessFile的方式和方法進(jìn)行了整理。供參考。
一、資源文件的讀取:
? ? ? 1) 從resource的raw中讀取文件數(shù)據(jù):
[java] ?view plaincopy
String?res?=? "" ;??? try {??? ??? ?????? ????InputStream?in?=?getResources().openRawResource(R.raw.test);??? ?? ?????? ????int ?length?=?in.available();????????? ?? ????byte ?[]?buffer?=? new ? byte [length];?????????? ?? ?????? ????in.read(buffer);??????????? ?? ?????? ????res?=?EncodingUtils.getString(buffer,?"BIG5" );??? ?????? ?????? ????in.close();?????????????? ?? ???}catch (Exception?e){??? ??????e.printStackTrace();??????????? ???}???
?2) 從resource的asset中讀取文件數(shù)據(jù)
[java] ?view plaincopy
String?fileName?=? "test.txt" ;? ?? String?res="" ;??? try {??? ?? ????? ???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();??????????? ?? ???}???
二、讀寫/data/data/<應(yīng)用程序名>目錄上的文件:
[java] ?view plaincopy
?? 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;??? ?? }?????
三、讀寫SD卡中的文件。也就是/mnt/sdcard/目錄下面的文件 :
[java] ?view plaincopy
?? 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();??? ???????}??? ???}??? ?? ???? ?? 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;??? }???
四、使用File類進(jìn)行文件的讀寫:
[java] ?view plaincopy
?? 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();??? }???
五、另外,File類還有下面一些常用的操作:
[java] ?view plaincopy
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();????
六、使用RandomAccessFile進(jìn)行文件的讀寫:
RandomAccessFile的使用方法比較靈活,功能也比較多,可以使用類似seek的方式可以跳轉(zhuǎn)到文件的任意位置,從文件指示器當(dāng)前位置開始讀寫。 它有兩種構(gòu)造方法 new RandomAccessFile(f,"rw");//讀寫方式 new RandomAccessFile(f,"r");//只讀方式 使用事例:
[java] ?view plaincopy
? ? ???? ???? import ?java.io.*;???? ???? public ? class ?RandomAccessFileDemo?{???? ?public ? static ? void ?main(String[]?args)? throws ?Exception?{???? ??RandomAccessFile?file?=?new ?RandomAccessFile( "file" ,? "rw" );???? ???? ??file.writeInt(20 ); ?? ??file.writeDouble(8.236598 ); ?? ??file.writeUTF("這是一個(gè)UTF字符串" ); ?? ??file.writeBoolean(true ); ?? ??file.writeShort(395 ); ?? ??file.writeLong(2325451l);?? ??file.writeUTF("又是一個(gè)UTF字符串" );???? ??file.writeFloat(35 .5f); ?? ??file.writeChar('a' ); ?? ???? ??file.seek(0 ); ?? ???? ???? ??System.out.println("——————從file文件指定位置讀數(shù)據(jù)——————" );???? ??System.out.println(file.readInt());???? ??System.out.println(file.readDouble());???? ??System.out.println(file.readUTF());???? ???? ??file.skipBytes(3 ); ?? ??System.out.println(file.readLong());???? ???? ??file.skipBytes(file.readShort());??? ??System.out.println(file.readFloat());???? ?????? ???? ??System.out.println("——————文件復(fù)制(從file到fileCopy)——————" );???? ??file.seek(0 );???? ??RandomAccessFile?fileCopy=new ?RandomAccessFile( "fileCopy" , "rw" );???? ??int ?len=( int )file.length(); ?? ??byte []?b= new ? byte [len];???? ??file.readFully(b);???? ??fileCopy.write(b);???? ??System.out.println("復(fù)制完成!" );???? ?}???? }????
七、讀取資源文件時(shí)能否實(shí)現(xiàn)類似于seek的方式可以跳轉(zhuǎn)到文件的任意位置,從指定的位置開始讀取指定的字節(jié)數(shù)呢?
答案是可以的。
在FileInputStream和InputStream中都有下面的函數(shù):
[java] ?view plaincopy
public ? long ?skip?( long ?byteCount);? ?? public ? int ?read?( byte []?buffer,? int ?offset,? int ?length);? ??
可以使用這兩個(gè)函數(shù)來實(shí)現(xiàn)類似于seek的操作,請看下面的測試代碼:
[java] ?view plaincopy
?? ?? public ?String?getRawString()? throws ?IOException?{?? ?????? ????String?str?=?null ;?? ?????? ????InputStream?in?=?getResources().openRawResource(R.raw.read_raw);?? ?????? ????int ?length?=?in.available();?? ????byte []?buffer?=? new ? byte [length];?? ?????? ????in.skip(2 );? ?? ????in.read(buffer,0 , 3 );? ?? ?????? ????in.skip(3 );? ?? ????in.read(buffer,0 , 3 );? ?? ?????? ?????? ????str?=?EncodingUtils.getString(buffer,?"BIG5" );?? ?????? ?????? ????in.close();?? ?????? ????return ?str;?? }??
從上面的實(shí)例可以看出skip函數(shù)有點(diǎn)類似于C語言中的seek操作,但它們之間有些不同。
需要注意的是:
1、skip函數(shù)始終是從當(dāng)前位置開始跳的。在實(shí)際應(yīng)用當(dāng)中還要再判斷一下該函數(shù)的返回值。
2、read函數(shù)也始終是當(dāng)前位置開始讀的。
3、另外,還可以使用reset函數(shù)將文件的當(dāng)前位置重置為0,也就是文件的開始位置。
如何得到文件的當(dāng)前位置?
我沒有找到相關(guān)的函數(shù)和方法,不知道怎么樣才能得到文件的當(dāng)前位置,貌似它也并不是太重要。
八、如何從FileInputStream中得到InputStream?
[java] ?view plaincopy
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();??? ??????}?? ?? }??
九、APK資源文件的大小不能超過1M,如果超過了怎么辦?我們可以將這個(gè)數(shù)據(jù)再復(fù)制到data目錄下,然后再使用。復(fù)制數(shù)據(jù)的代碼如下:
[java] ?view plaincopy
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;?? ????}?????
轉(zhuǎn)載時(shí)請注明出處:http://blog.csdn.net/ztp800201/article/details/7322110
總結(jié):
1、apk中有兩種資源文件,使用兩種不同的方式進(jìn)行打開使用。 raw使用InputStream in = getResources().openRawResource(R.raw.test); asset使用InputStream in = getResources().getAssets().open(fileName);
這些數(shù)據(jù)只能讀取,不能寫入。更重要的是該目錄下的文件大小不能超過1M。
同時(shí),需要注意的是,在使用InputStream的時(shí)候需要在函數(shù)名稱后加上throws IOException。
2、SD卡中的文件使用FileInputStream和FileOutputStream進(jìn)行文件的操作。 3、存放在數(shù)據(jù)區(qū)(/data/data/..)的文件只能使用openFileOutput和openFileInput進(jìn)行操作。 注意不能使用FileInputStream和FileOutputStream進(jìn)行文件的操作。 4、RandomAccessFile類僅限于文件的操作,不能訪問其他IO設(shè)備。它可以跳轉(zhuǎn)到文件的任意位置,從當(dāng)前位置開始讀寫。
5、InputStream和FileInputStream都可以使用skip和read(buffre,offset,length)函數(shù)來實(shí)現(xiàn)文件的隨機(jī)讀取。
總結(jié)
以上是生活随笔 為你收集整理的Android - 文件读写操作 总结 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。