天天看點

Java位元組流詳解位元組流

位元組流

位元組流不僅可以操作位元組流還可以操作字元,以及其他的媒體檔案

InputStream位元組輸入流

InputStream類是位元組輸入流的基類

Java位元組流詳解位元組流

InputStream類

序号 方法描述
1 int available() 從下一次調用此輸入流的方法傳回可從該輸入流讀取(或跳過)的位元組數,而不會阻塞。
2 void close() 關閉此輸入流并釋放與流相關聯的任何系統資源。
3 void mark(int readlimit) 标記此輸入流中的目前位置。
4 boolean markSupported() 測試此輸入流是否支援 mark和 reset方法。
5 abstract int read() 從輸入流讀取資料的下一個位元組。
6 int read(byte[] b) 從輸入流中讀取一些位元組數,并将它們存儲到緩沖器陣列 b 。
7 int read(byte[] b, int off, int len) 從輸入流讀取最多 len個位元組的資料到位元組數組。
8 byte[] readAllBytes() 從輸入流讀取所有剩餘位元組。
9 int readNBytes( byte [] b, int off, int len)i 将所請求的位元組數從輸入流讀入給定的位元組數組。
10 void reset() 将此流重新定位到最後在此輸入流上調用 mark方法時的位置。
11 long skip(``long n) 跳過并丢棄來自此輸入流的 n位元組的資料。
12 long transferTo(OutputStream out) 從該輸入流中讀取所有位元組,并按讀取的順序将位元組寫入給定的輸出流。

ByteInputStream類

  • 位元組數組輸入流在記憶體中建立一個位元組數組緩沖區,從輸入流讀取的資料儲存在該位元組數組緩沖區中

    建立方式:

    1、接收位元組數組作為參數
    ByteArrayInputStream bas = new ByteArrayInputStream(byte [] a)
    2 、接收一個位元組數組和兩個整型變量 off、len,off表示第一個讀取的位元組,len表示讀取位元組的長度
    ByteArrayInputStream bas = new ByteArrayInputStream(byte [] a,int off,int len)

    常用方法

    序号 方法描述
    1 public int read() 從此輸入流中讀取下一個資料位元組
    2 public int read(byte[] r,int off,int len) 将最多len個資料位元組從此輸入流讀入位元組數組
    3 public int available() 傳回可不發生阻塞地從此輸入流讀取的位元組數
    4 public void mark (int read)設定流中的目前标記位置
    5 public long skip(long n) 從此輸入流中跳過n個輸入位元組

    實列

    import java.io.ByteArrayInputStream;
      import java.io.ByteArrayOutputStream;
      import java.io.IOException;
      
      /**
       * @program: IOtest
       * @description: 測試ByteArrayInputStream
       * @author: 雨沐淋風
       * @create: 2020-10-23
       **/
      public class TestByteArrayInputStream {
          public static void main(String[] args) throws IOException {
              ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
              while (bOutput.size() != 10){
                  bOutput.write(System.in.read());
              }
      
              byte[] bytes = bOutput.toByteArray();
              System.out.println("Print the content");
      
              for (int i = 0; i < bytes.length; i++) {
                  System.out.println((char)bytes[i] + "  ");
              }
              System.out.println("     ");
      
              int c;
              ByteArrayInputStream bInput = new ByteArrayInputStream(bytes);
      
              System.out.println("Converting characters to Upper case " );
              for(int y = 0 ; y < 1; y++ ) {
                  while(( c= bInput.read())!= -1) {
                      System.out.println(Character.toUpperCase((char)c));
                  }
                  bInput.reset();
              }
          }
      }
               
  • 運作結果
    abcdwefijijiji
        Print the content
        a  
        b  
        c  
        d  
        w  
        e  
        f  
        i  
        j  
        i  
             
        Converting characters to Upper case 
        A
        B
        C
        D
        W
        E
        F
        I
        J
        I
               

FileInputStream 類

  • FileInputStream的構造方法需要指定檔案的來源,通過打開一個到實際檔案的連接配接來建立一個FileInputStream,該檔案通過檔案系統中的 File 對象 file 指定。

    建立方式:

    1、通過打開與實際檔案的連接配接來建立一個 FileInputStream ,該檔案由檔案系統中的 File對象 file命名。
    FileInputStream fis = new FileInputStream(File file)
    2、通過使用檔案描述符 fdObj建立 FileInputStream ,該檔案描述符表示與檔案系統中的實際檔案的現有連接配接。
    FileInputStream fis = new FileInputStream(FileDescriptor fdObj)
    3、通過打開與實際檔案的連接配接來建立一個 FileInputStream ,該檔案由檔案系統中的路徑名 name命名。
    FileInputStream fis = new FileInputStream(String name)

    常用方法

    傳回類型 方法名 描述
    int available() 傳回從此輸入流中科院讀取的剩餘位元組數的估值,而不會被下一次調用此輸入流的方法阻塞
    void close() 關閉此檔案輸入流并釋放與流相關的任何系統資源
    protected void finalize() 確定當這個檔案輸入流的close方法沒有更多的應用時被調用
    FileChannel getChannle() 傳回與此檔案輸入流相關聯的唯一FileChannel對象
    FileDescriptor getFD() 傳回表示與此FileInputStrem正在使用的檔案系統中檔案的連接配接的FileDescriptor對象
    int read() 從該輸入流讀取一個位元組的資料
    int read(byte[] b) 從該輸入流讀取最多b.length個位元組的資料為位元組數組
    int read(byte[] b,int off,int len) 從該輸入流讀取最多len位元組的資料為位元組數組
    long skip(long n) 跳過從輸入流中丢棄n位元組的資料

    運用執行個體

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /**
     * @program: IOtest
     * @description: 測試FIleInputStream
     * @author: 雨沐淋風
     * @create: 2020-10-23
     **/
    public class TestFieInputStream {
        public static void main(String[] args) {
    
            FileInputStream fileInput = null;
            try {
                // test.txt 内容:InputStream test
                fileInput = new FileInputStream("test.txt");
                byte[] bytes = new byte[1024]; //一次讀取多個位元組
                int len = 0;
                try {
    //                if ((len = fileInput.read(bytes,2,5)) != -1) {
    //                    System.out.println(new String(bytes));
    //                }
    //               結果:  Input                                                                 
                    if ((len = fileInput.read(bytes)) != -1) {
                        System.out.println(new String(bytes));
                    }
    //               結果: InputStream test                       
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
    
                try {
                    if (fileInput != null) {
                        fileInput.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
        }
    }
    
               
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /**
     * @program: IOtest
     * @description: 測試FIleInputStream
     * @author: 雨沐淋風
     * @create: 2020-10-23
     **/
    public class TestFieInputStream {
        public static void main(String[] args) {FileInputStream fileInputStream = null;
            try {
                // test.txt 内容:InputStream test
                fileInputStream = new FileInputStream("test.txt");
                try {
                    //跳過前面9個字元
                    long len = fileInputStream.skip(9);
                    //擷取流中可以讀取的剩餘位元組數
                    int available = fileInputStream.available();
                    System.out.println(available);
                    int ch = 0;
                    // 調用read()方法,一次讀一個位元組,自動往下讀
                    while ((ch = fileInputStream.read()) != -1){
                        System.out.println((char)ch);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally {
                try {
                    if (fileInputStream != null){
                        fileInputStream.close();
                    }    
                }catch (IOException e){
                    throw new RuntimeException("關閉檔案異常");
                }   
            }
        }
    }
               
    7
    a
    m
     
    t
    e
    s
    t
               

OutputStream 位元組輸出流

OutputStream是一個抽象類,表示位元組輸出流的超類。輸出流接收到輸出位元組并将其發送到某個接收器上

Java位元組流詳解位元組流

常用方法

傳回類型 方法名 描述
void close() 關閉此輸出流并釋放與此流相關聯的任何資源
void flush() 重新整理此輸出流并強制任何緩沖的輸出位元組被寫出
void write(byte[] b) 将b.length位元組從位元組數組寫入此輸出流
void write(byte[] b,int off,int len) 從指定的位元組數組寫入len個位元組,從偏移量為off的位置開始輸出到輸出流
abstract write(int b) 将指定的位元組寫入此輸出流

FileInputStream類

檔案輸出流是用于将資料寫入到輸出流File或一個FileDescriptor。檔案是否可用或者可能被建立取決與底層平台。特别是有些平台之被允許一次隻能打開一個檔案來寫入FileOutputStream。在這種情況下,如果所涉及的檔案已經打開,則此類中的構造函數将失敗

FileOutputStream用于寫入諸如圖像資料的原始位元組流。對于寫入字元流,考慮使用Filewriter。

構造方法

方法名 描述
FileOutputStream(File file) 建立檔案輸出流以寫入由指定的File對象表示的檔案
FileOutputStream(File file,boolean append) 建立檔案輸出流以寫入有指定的File對象表示檔案,後面append參數true表示後面追加,false表示不追加覆寫原檔案
FileOutputStream(FileDescriptor fobj) 建立檔案輸出流以寫入指定的檔案描述符,表示與檔案系統中實際檔案的現有連接配接
FileOutputStream(String name) 建立檔案輸出流以指定的名稱寫入檔案
FileOutputStream(String name,boolean append) 建立檔案輸出流以指定的名稱寫入檔案,append參數:true表示原檔案後面追加,false表示覆寫原檔案

常用方法

傳回類型 方法名 描述
void close() 關閉檔案輸出流并釋放與此流相關聯的任何系統資源
protected void fianlize() 清理與檔案的連接配接,并確定當沒有更多的引用此流時,将調用此檔案輸出流的close方法
FileChannel getFileChannel() 傳回與此檔案輸出流相關聯的唯一的FileChannel對象
FileDescriptor getFD() 傳回與此輸出流相關聯的檔案描述符。
void write(byte[] b) 将b.length個位元組從指定的位元組數組寫入此檔案輸出流。
void write(byte[] b,int off,int len) 将len個位元組從位置偏移量為off的位置指定位元組數組寫入此輸出流
void write(int b) 将指定的位元組寫入此檔案輸出流中

代碼示例

import java.io.*;

/**
 * @program: IOtest
 * @description:測試FileOuputStream
 * @author: 雨沐淋風
 * @create: 2020-10-23
 **/
public class TestFileOutputStream {
    public static void main(String[] args) {
        //建立一個新檔案
        File file = new File("TestFileOutputStream.txt");
        try {
            //建立file對應的FileOutputStream對象
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            PrintWriter printWriter = new PrintWriter(fileOutputStream);
            printWriter.print("TestOutputStream");
            printWriter.close();
			//建立file對應的FileOutputStream對象,第二參數是true表示在原檔案的後面追加内容
            FileOutputStream fileOutputStream1 = new FileOutputStream(file, true);
            PrintStream printStream = new PrintStream(fileOutputStream1);
            printStream.print("  append");
            printStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
           
import java.io.*;

/**
 * @program: IOtest
 * @description:将test.txt檔案的内容拷貝到copy.txt中
 * @author: 雨沐淋風
 * @create: 2020-10-23
 **/
public class TestFileOutputStream {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream("test.txt");
            fileOutputStream = new FileOutputStream("copy.txt");
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1){
                fileOutputStream.write(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (fileOutputStream != null){
                    fileOutputStream.close();
                }
                if(fileInputStream !=null){
                    fileInputStream.close();
                }
            }catch (IOException e){
                throw new RuntimeException("關閉檔案異常");
            }
        }
    }
}

           
try {
            if (fileOutputStream != null){
                fileOutputStream.close();
            }
            if(fileInputStream !=null){
                fileInputStream.close();
            }
        }catch (IOException e){
            throw new RuntimeException("關閉檔案異常");
        }
    }
}
           

}