最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android編程之文件讀寫(xiě)操作與技巧總結(jié)【經(jīng)典收藏】

 更新時(shí)間:2016年06月14日 09:16:57   作者:ztp800201  
這篇文章主要介紹了Android編程之文件讀寫(xiě)操作與技巧,結(jié)合實(shí)例形式總結(jié)分析了Android常見(jiàn)的文件與目錄的讀寫(xiě)操作,及相關(guān)函數(shù)的使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下

本文實(shí)例總結(jié)了Android文件讀寫(xiě)操作。分享給大家供大家參考,具體如下:

在Android中的文件放在不同位置,它們的讀取方式也有一些不同。
本文對(duì)android中對(duì)資源文件的讀取、數(shù)據(jù)區(qū)文件的讀取、SD卡文件的讀取及RandomAccessFile的方式和方法進(jìn)行了整理。供參考。

一、資源文件的讀取:

1) 從resource的raw中讀取文件數(shù)據(jù):

String res = "";
try{
  //得到資源中的Raw數(shù)據(jù)流
  InputStream in = getResources().openRawResource(R.raw.test);
  //得到數(shù)據(jù)的大小
  int length = in.available();
  byte [] buffer = new byte[length];
  //讀取數(shù)據(jù)
  in.read(buffer);
  //依test.txt的編碼類型選擇合適的編碼,如果不調(diào)整會(huì)亂碼
  res = EncodingUtils.getString(buffer, "BIG5");
  //關(guān)閉
  in.close();
}catch(Exception e){
  e.printStackTrace();
}

2) 從resource的asset中讀取文件數(shù)據(jù)

String fileName = "test.txt"; //文件名字
String res="";
try{
  //得到資源中的asset數(shù)據(jù)流
  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();
}

二、讀寫(xiě)/data/data/<應(yīng)用程序名>目錄上的文件:

//寫(xiě)數(shù)據(jù)
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();
    }
}
//讀數(shù)據(jù)
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;
}

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

//寫(xiě)數(shù)據(jù)到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;
}

四、使用File類進(jìn)行文件的讀寫(xiě):

//讀文件
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;
}
//寫(xiě)文件
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();
}

五、另外,F(xiàn)ile類還有下面一些常用的操作:

String Name = File.getName(); //獲得文件或文件夾的名稱:
String parentPath = File.getParent(); //獲得文件或文件夾的父目錄
String path = File.getAbsoultePath();//絕對(duì)路經(jīng)
String path = File.getPath();//相對(duì)路經(jīng)
File.createNewFile();//建立文件
File.mkDir(); //建立文件夾
File.isDirectory(); //判斷是文件或文件夾
File[] files = File.listFiles(); //列出文件夾下的所有文件和文件夾名
File.renameTo(dest); //修改文件夾和文件名
File.delete(); //刪除文件夾或文件

六、使用RandomAccessFile進(jìn)行文件的讀寫(xiě):

RandomAccessFile的使用方法比較靈活,功能也比較多,可以使用類似seek的方式可以跳轉(zhuǎn)到文件的任意位置,從文件指示器當(dāng)前位置開(kāi)始讀寫(xiě)。

它有兩種構(gòu)造方法

new RandomAccessFile(f,"rw");//讀寫(xiě)方式
new RandomAccessFile(f,"r");//只讀方式

使用事例:

/*
 * 程序功能:演示了RandomAccessFile類的操作,同時(shí)實(shí)現(xiàn)了一個(gè)文件復(fù)制操作。
 */
import java.io.*;
public class RandomAccessFileDemo {
 public static void main(String[] args) throws Exception {
 RandomAccessFile file = new RandomAccessFile("file", "rw");
 // 以下向file文件中寫(xiě)數(shù)據(jù)
 file.writeInt(20);// 占4個(gè)字節(jié)
 file.writeDouble(8.236598);// 占8個(gè)字節(jié)
 file.writeUTF("這是一個(gè)UTF字符串");// 這個(gè)長(zhǎng)度寫(xiě)在當(dāng)前文件指針的前兩個(gè)字節(jié)處,可用readShort()讀取
 file.writeBoolean(true);// 占1個(gè)字節(jié)
 file.writeShort(395);// 占2個(gè)字節(jié)
 file.writeLong(2325451l);// 占8個(gè)字節(jié)
 file.writeUTF("又是一個(gè)UTF字符串");
 file.writeFloat(35.5f);// 占4個(gè)字節(jié)
 file.writeChar('a');// 占2個(gè)字節(jié)
 file.seek(0);// 把文件指針位置設(shè)置到文件起始處
 // 以下從file文件中讀數(shù)據(jù),要注意文件指針的位置
 System.out.println("——————從file文件指定位置讀數(shù)據(jù)——————");
 System.out.println(file.readInt());
 System.out.println(file.readDouble());
 System.out.println(file.readUTF());
 file.skipBytes(3);// 將文件指針跳過(guò)3個(gè)字節(jié),本例中即跳過(guò)了一個(gè)boolean值和short值。
 System.out.println(file.readLong());
 file.skipBytes(file.readShort()); // 跳過(guò)文件中“又是一個(gè)UTF字符串”所占字節(jié),注意readShort()方法會(huì)移動(dòng)文件指針,所以不用加2。
 System.out.println(file.readFloat());
 //以下演示文件復(fù)制操作
 System.out.println("——————文件復(fù)制(從file到fileCopy)——————");
 file.seek(0);
 RandomAccessFile fileCopy=new RandomAccessFile("fileCopy","rw");
 int len=(int)file.length();//取得文件長(zhǎng)度(字節(jié)數(shù))
 byte[] b=new byte[len];
 file.readFully(b);
 fileCopy.write(b);
 System.out.println("復(fù)制完成!");
 }
}

七、讀取資源文件時(shí)能否實(shí)現(xiàn)類似于seek的方式可以跳轉(zhuǎn)到文件的任意位置,從指定的位置開(kāi)始讀取指定的字節(jié)數(shù)呢?
答案是可以的。

在FileInputStream和InputStream中都有下面的函數(shù):

public long skip (long byteCount); //從數(shù)據(jù)流中跳過(guò)n個(gè)字節(jié)
public int read (byte[] buffer, int offset, int length); //從數(shù)據(jù)流中讀取length數(shù)據(jù)存在buffer的offset開(kāi)始的位置。offset是相對(duì)于buffer的開(kāi)始位置的,不是數(shù)據(jù)流。

可以使用這兩個(gè)函數(shù)來(lái)實(shí)現(xiàn)類似于seek的操作,請(qǐng)看下面的測(cè)試代碼:

//其中read_raw是一個(gè)txt文件,存放在raw目錄下。
//read_raw.txt文件的內(nèi)容是:"ABCDEFGHIJKLMNOPQRST"
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); //跳過(guò)兩個(gè)字節(jié)
  in.read(buffer,0,3); //讀三個(gè)字節(jié)
  in.skip(3); //跳過(guò)三個(gè)字節(jié)
  in.read(buffer,0,3); //讀三個(gè)字節(jié)
  //最后str="IJK"
  str = EncodingUtils.getString(buffer, "BIG5");
  in.close();
  return str;
}

從上面的實(shí)例可以看出skip函數(shù)有點(diǎn)類似于C語(yǔ)言中的seek操作,但它們之間有些不同。

需要注意的是:

1、skip函數(shù)始終是從當(dāng)前位置開(kāi)始跳的。在實(shí)際應(yīng)用當(dāng)中還要再判斷一下該函數(shù)的返回值。

2、read函數(shù)也始終是當(dāng)前位置開(kāi)始讀的。

3、另外,還可以使用reset函數(shù)將文件的當(dāng)前位置重置為0,也就是文件的開(kāi)始位置。

如何得到文件的當(dāng)前位置?

我沒(méi)有找到相關(guān)的函數(shù)和方法,不知道怎么樣才能得到文件的當(dāng)前位置,貌似它也并不是太重要。

八、如何從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();
   }
}

九、APK資源文件的大小不能超過(guò)1M,如果超過(guò)了怎么辦?我們可以將這個(gè)數(shù)據(jù)再?gòu)?fù)制到data目錄下,然后再使用。復(fù)制數(shù)據(jù)的代碼如下:

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;
}

總結(jié):

1、apk中有兩種資源文件,使用兩種不同的方式進(jìn)行打開(kāi)使用。

raw使用:

InputStream in = getResources().openRawResource(R.raw.test);

asset使用:

InputStream in = getResources().getAssets().open(fileName);

這些數(shù)據(jù)只能讀取,不能寫(xiě)入。更重要的是該目錄下的文件大小不能超過(guò)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類僅限于文件的操作,不能訪問(wèn)其他IO設(shè)備。它可以跳轉(zhuǎn)到文件的任意位置,從當(dāng)前位置開(kāi)始讀寫(xiě)。

5、InputStream和FileInputStream都可以使用skip和read(buffre,offset,length)函數(shù)來(lái)實(shí)現(xiàn)文件的隨機(jī)讀取。

更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android文件操作技巧匯總》、《Android編程開(kāi)發(fā)之SD卡操作方法匯總》、《Android開(kāi)發(fā)入門(mén)與進(jìn)階教程》、《Android資源操作技巧匯總》、《Android視圖View技巧總結(jié)》及《Android控件用法總結(jié)

希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • Android通過(guò)Webservice操作sqlserver數(shù)據(jù)庫(kù)實(shí)例代碼

    Android通過(guò)Webservice操作sqlserver數(shù)據(jù)庫(kù)實(shí)例代碼

    這篇文章主要介紹了Android通過(guò)Webservice操作sqlserver數(shù)據(jù)庫(kù)的相關(guān)知識(shí),對(duì)webservice操作數(shù)據(jù)庫(kù)相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧
    2016-01-01
  • android仿支付寶、微信密碼輸入框效果

    android仿支付寶、微信密碼輸入框效果

    這篇文章主要為大家詳細(xì)介紹了android仿支付寶、微信密碼輸入框效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • Android 簡(jiǎn)單服務(wù)定位器模式實(shí)現(xiàn)

    Android 簡(jiǎn)單服務(wù)定位器模式實(shí)現(xiàn)

    這篇文章主要介紹了Android 簡(jiǎn)單服務(wù)定位器模式實(shí)現(xiàn),幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下
    2021-03-03
  • AndroidStudio Gradle第三依賴統(tǒng)一管理的實(shí)現(xiàn)方法

    AndroidStudio Gradle第三依賴統(tǒng)一管理的實(shí)現(xiàn)方法

    這篇文章主要介紹了AndroidStudio Gradle第三依賴統(tǒng)一管理的實(shí)現(xiàn)方法,需要的朋友可以參考下
    2017-09-09
  • Flutter 路由插件fluro的使用

    Flutter 路由插件fluro的使用

    使用原生的路由基本上能夠滿足大部分需求,但如果想要對(duì)頁(yè)面做類似瀏覽器 url 那樣的路由,或者控制頁(yè)面跳轉(zhuǎn)的轉(zhuǎn)場(chǎng)動(dòng)畫(huà),那么原生的路由需要做不少的改造。在 pub 上,有優(yōu)秀的路由插件 fluro 解決這類問(wèn)題。本文介紹該插件的使用方法
    2021-06-06
  • android播放gif格式圖片示例

    android播放gif格式圖片示例

    這篇文章主要介紹了android播放gif格式圖片的方法,大家參考使用吧
    2014-01-01
  • Android SharedPreferences實(shí)現(xiàn)記住密碼和自動(dòng)登錄

    Android SharedPreferences實(shí)現(xiàn)記住密碼和自動(dòng)登錄

    這篇文章主要為大家詳細(xì)介紹了Android SharedPreferences實(shí)現(xiàn)記住密碼和自動(dòng)登錄,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-05-05
  • Android控件之菜單的創(chuàng)建方式

    Android控件之菜單的創(chuàng)建方式

    本文給大家分享android控件菜單的兩種創(chuàng)建方式,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧
    2017-09-09
  • Android三種雙屏異顯實(shí)現(xiàn)方法介紹

    Android三種雙屏異顯實(shí)現(xiàn)方法介紹

    現(xiàn)在越來(lái)越多的Android設(shè)備有多個(gè)屏幕,雙屏異顯應(yīng)用場(chǎng)景最多的應(yīng)該就是類似于收銀平臺(tái)那種設(shè)備,在主屏上店員能夠?qū)c(diǎn)商品進(jìn)行選擇錄入,副屏則是展示給我們的賬單詳情,但是它只通過(guò)了一個(gè)軟件系統(tǒng)就實(shí)現(xiàn)了雙屏異顯這個(gè)功能,而Presentation正是這其中的關(guān)鍵
    2023-01-01
  • Android中絕對(duì)音量和相對(duì)音量設(shè)置

    Android中絕對(duì)音量和相對(duì)音量設(shè)置

    大家好,本篇文章主要講的是Android中絕對(duì)音量和相對(duì)音量設(shè)置,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下
    2022-01-01

最新評(píng)論

吉林省| 镇巴县| 北宁市| 平武县| 永胜县| 安康市| 通江县| 江都市| 正阳县| 儋州市| 金山区| 华容县| 杨浦区| 万年县| 黄梅县| 陇川县| 庆阳市| 息烽县| 乐亭县| 浦城县| 营山县| 苏尼特左旗| 揭阳市| 阿拉善左旗| 海盐县| 苍南县| 正宁县| 武威市| 高雄市| 巫山县| 杭州市| 台北市| 西乌| 岑巩县| 邵阳市| 南城县| 台湾省| 崇仁县| 靖边县| 沈阳市| 安乡县|