Java IO中的其他讀寫流

RandomAccessFile
  • 構造方法

      //var1 文件路徑,var 文件的讀寫模式 "r"只讀,"w"只寫,"rw"讀寫
      public RandomAccessFile(String var1, String var2) throws FileNotFoundException {
              this(var1 != null?new File(var1):null, var2);
          }
      //傳文件,和模式
      public RandomAccessFile(File var1, String var2) throws FileNotFoundException {
    
          }
    
  • 其他常用方法

      public void close () 關閉操作
    
      public int read ( byte[] b)將內容讀取到一個byte數組之中
    
      public final byte readByte () 讀取一個字節
    
      public final int readInt () 從文件中讀取整型數據。
    
      public void seek ( long pos)設置讀指針的位置。
    
      public final void writeBytes (String s)將一個字符串寫入到文件之中,按字節的方式處理。
    
      public final void writeInt ( int v)將一個int型數據寫入文件,長度為4位。
    
      public int skipBytes ( int n)指針跳過多少個字節。
    
RandomAccessFile 讀寫案例
  • 文件路徑

        //文件路徑
          public static final String PATH = "/Volumes/huang/studyfromGitHub/JavaForAndroid/JavaForAndroid/series11/src/main/java/files/testRAF.txt";
    
  •      /**
              *
              */
             private static void testWrite() {
                 RandomAccessFile accessFile = null;
                 try {
                     //讀寫模式創建實例
                     accessFile = new RandomAccessFile(PATH, "rw");
                     //讀取文件長度
                     System.out.println(accessFile.length() + " B");//0B
    
                     //將文件指針移動中間位置
                     accessFile.seek(accessFile.length() / 2);
                     String name = null;
                     int age = 0;// int 的長度為4
                     float money = 1.2f;// float 的長度為4
                     //double長度為8
    
                     name = "name1";// 長度為5de字符串
                     age = 20;
                     money = 23.5f;
                     accessFile.writeBytes(name);
                     //讀取文件長度
                     System.out.println(accessFile.length() + "B");//5B
                     accessFile.writeInt(age);
                     System.out.println(accessFile.length() + "B");//9B
                     accessFile.writeFloat(money);
                     System.out.println(accessFile.length() + "B");//13B
                     System.out.println("================================");
    
                     name = "name2";// 長度為5de字符串
                     age = 21;
                     money = 24.5f;
                     accessFile.writeBytes(name);
                     System.out.println(accessFile.length() + "B");//18B
                     accessFile.writeInt(age);
                     System.out.println(accessFile.length() + "B");//22B
                     accessFile.writeFloat(money);
                     System.out.println(accessFile.length() + "B");//26B
    
                     //accessFile.writeUTF("hello,你好!");
                     //注:從中間寫入的數據是覆蓋后面的內容,因此在寫數據時,盡量追加在內容之后
                 } catch (Exception e) {
                     e.printStackTrace();
                 } finally {
                     try {
                         accessFile.close();
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                 }
             }
    
  •   /**
           * 讀
           */
          private static void testRead() {
              RandomAccessFile accessFile = null;
              //讀寫模式創建實例
              try {
                  accessFile = new RandomAccessFile(PATH, "r");//只讀模式創建實例
                  String name = null;
                  int age = 0;
                  float money = 0.0f;
                  byte[] bytes = new byte[5];
                  //假如要先讀第二個人的信息
                  accessFile.skipBytes(13);//則跳過前13字節
                  for (int i = 0; i < bytes.length; i++) {
                      bytes[i] = accessFile.readByte();//讀取一個字節
                  }
                  name = new String(bytes);
                  age = accessFile.readInt();
                  money = accessFile.readFloat();
                  System.out.println("name2:-->" + name + "\t" + age + "\t" + money);
                  //讀第一個
                  accessFile.seek(0);//指針回到0
                  //假如要先讀第二個人的信息
                  for (int i = 0; i < bytes.length; i++) {
                      bytes[i] = accessFile.readByte();//讀取一個字節
                  }
                  name = new String(bytes);
                  age = accessFile.readInt();
                  money = accessFile.readFloat();
                  System.out.println("name1:-->" + name + "\t" + age + "\t" + money);
              } catch (Exception e) {
                  e.printStackTrace();
              }finally {
                  try {
                      accessFile.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          }
    
  • 讀的運行結果


DataOutputStream(數據輸出流)、DataInputStream(數據輸入流)
DataOutputStream

構造方法

     //傳入一個字節輸出流
     public DataOutputStream(OutputStream var1) {
            super(var1);
        }
用法案例
  • 文件路徑

          public static final String PATH = "/Volumes/huang/studyfromGitHub/JavaForAndroid/JavaForAndroid/series11/src/main/java/files/testOutput.txt";
    
  •       /**
               * DataOutputStream 寫
               */
              private static void write() {
                  DataOutputStream outputStream = null;
                  try {
                      //傳入字節流實例獲取對象實例
                      outputStream = new DataOutputStream(new FileOutputStream(PATH));
                      //寫入基本數據
                      outputStream.writeUTF("你好,Java"); //寫入utf-8編碼字符串
                      outputStream.writeInt(10);
                      outputStream.writeInt(34);
                      outputStream.writeChar('a');
                      outputStream.writeBoolean(true);
                  } catch (Exception e) {
                      e.printStackTrace();
                  }finally {
                      try {
                          outputStream.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
    
  •   /**
           *
           */
          private static void read() {
              DataInputStream inputStream=null;
              try {
                  inputStream=new DataInputStream(new FileInputStream(PATH));
                  //2. 讀取數據
                  String txt=inputStream.readUTF();//讀取utf-8編碼的字符串
                  int a=inputStream.readInt();
                  int b=inputStream.readInt();
                  int num=inputStream.readChar();
                  boolean flag=inputStream.readBoolean();
    
                  System.out.println(txt+"\r\n"+a+" "+b+","+num+","+flag);
    
              } catch (Exception e) {
                  e.printStackTrace();
              }finally {
                  //關閉流
                  try {
                      inputStream.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          }
    
  • 讀結果


ByteArrayInputStream、ByteArrayOutputStream很常用的兩個類
ByteArrayInputStream

構造方法

//使用一個字節數組當中所有的數據做為數據源
public ByteArrayInputStream(byte[] var1) {
        .....
    }
//從數組當中的第offset開始,一直取出length個這個字節做為數據源。
public ByteArrayInputStream(byte[] var1, int var2, int var3) {
      ....
    }
ByteArrayOutputStream

構造方法

//創建一個32個字節的緩沖區
public ByteArrayOutputStream() {
        this(32);
    }
//根據參數指定大小創建緩沖區
public ByteArrayOutputStream(int var1) {
        if(var1 < 0) {
            throw new IllegalArgumentException("Negative initial size: " + var1);
        } else {
            this.buf = new byte[var1];
        }
    }

這兩個構造函數創建的緩沖區大小在數據過多的時候都會自動增長。

案例運用
/**
 * ByteArrayOutputStream拷貝本文件內容
 */
public class Demo9 {
    //源文件路徑
    public static final String sourcePath = "/Volumes/huang/studyfromGitHub/JavaForAndroid/JavaForAndroid/series11/src/main/java/com/example/Demo9.java";

    public static void main(String[] args) {
        try {
            //得到字節流
            FileInputStream inputStream = new FileInputStream(sourcePath);

            //將字節流轉成字符流
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

            //將字節流包裝成一個緩沖字符流
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            //創建內存流對象--內存輸出流
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(inputStream.available());

            //將字節流轉換成字符流
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(arrayOutputStream);

            //將字符流包裝成緩沖字符流--BufferedWriter
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

            String msg = null;
            while ((msg = bufferedReader.readLine()) != null) {
                bufferedWriter.write(msg);//向內存中寫入數據
                bufferedWriter.newLine();
                bufferedWriter.flush();//將緩沖區的數據寫入到內存流中使用的內存區中
            }
            byte[] bytes = arrayOutputStream.toByteArray();
            System.out.println(new String(bytes));

            //關閉流
            bufferedReader.close();
            bufferedWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,527評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,687評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,640評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,957評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,682評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,011評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,009評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,183評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,714評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,435評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,665評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,148評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,838評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,251評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,588評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,379評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,627評論 2 380

推薦閱讀更多精彩內容