Core Java - 流(Stream) - 位元組流和字元流(一)

來源:互聯網
上載者:User

標籤:概述   檔案中   print   寫入   try   off   str   []   get   

0. 概述:

Java中基於流的I/O構建在4個抽象類別之上, 其中2個是位元組流,另外2個是字元流。

位元組流:

InputStream / OutputStream

當操作位元組或其它二進位對象時,應當使用位元組流。

 

字元流:

Reader / Writer

當操作字元或字串時,應當使用字元流。

 

1. InputStream

InputStream:   輸入位元組流,它是一個抽象類別。

常用主要方法:

int read()

返回代表下一個可用位元組的整數,當檔案達到末尾時,返回-1。

 

int read(bute buffer[])

嘗試讀取buffer.length個位元組到buffer中,返回實際成功讀取的位元組數;檔案到末尾返回-1。

 

int read(bute buffer[], int offset, int numBytes)

嘗試讀取numBytes個位元組到buffer中,從buffer[offset]開始儲存讀取的位元組;

返回實際成功讀取的位元組數;檔案到末尾返回-1。

 

2. OutputStream

OutputStream: 輸出位元組流,它是一個抽象類別。

常用主要方法:

void write(int b)

向輸出資料流中寫入單個位元組。

 

void write(byte buffer[])

向輸出資料流中寫入一個完整的位元組數組。

 

void write(byte buffer[], int offset, int numBytes)

從buffer[offset]開始將numBytes個位元組寫入輸出資料流中。

 

void flush()

結束輸出狀態,重新整理輸出緩衝區。

 

3. FileInputStream

檔案讀取位元組流。

常用建構函式:

FileInputStream(String filePath)  (更常用)

FileInputStream(File fileObj)

一個同構輸入資料流來讀取檔案內容的例子,示範了3種方式(單位元組讀取, 位元組數組讀取, 忽略部分位元組讀取)

代碼如下:

package corejava8.io.stream;import java.io.*;public class FileInputStreamDemo {    public static void main(String args[]) {        int size;        // Use try-with-resources to close the stream        try (FileInputStream f = new FileInputStream("src/corejava8/io/stream/FileInputStreamDemo.java")) {            System.out.println("Total Available Bytes: " + (size = f.available()));            int n = size / 40;                        // 通過迴圈每次單位元組讀取            System.out.println("First " + n + " bytes of the file one read() at a time");            for (int i = 0; i < n; i++) {                System.out.print((char) f.read());            }            System.out.println("\nStill Available: " + f.available());            System.out.println("--------------------------------------------------------------");                        // 位元組數組讀取            System.out.println("Reading the next " + n + " with one read(b[])");            byte b[] = new byte[n];            if (f.read(b) != n) {                System.err.println("couldn’t read " + n + " bytes.");            }            System.out.println(new String(b, 0, n));            System.out.println("\nStill Available: " + (size = f.available()));            System.out.println("--------------------------------------------------------------");                        // 忽略部分位元組讀取            System.out.println("Skipping half of remaining bytes with skip()");            f.skip(size / 2);            System.out.println("Still Available: " + f.available());            System.out.println("Reading " + n / 2 + " into the end of array");            if (f.read(b, n / 2, n / 2) != n / 2) {                System.err.println("couldn‘t read " + n / 2 + " bytes.");            }            System.out.println(new String(b, 0, b.length));            System.out.println("\nStill Available: " + f.available());        } catch (IOException e) {            System.out.println("I/O Error: " + e);        }    }}

運行結果如下:

Total Available Bytes: 1704

First 42 bytes of the file one read() at a time

package corejava8.io.stream;

 

import java.

Still Available: 1662

--------------------------------------------------------------

Reading the next 42 with one read(b[])

io.*;

 

public class FileInputStreamDemo {

 

 

Still Available: 1620

--------------------------------------------------------------

Skipping half of remaining bytes with skip()

Still Available: 810

Reading 21 into the end of array

io.*;

 

public class Fm.err.println("couldn

 

Still Available: 789

 

4. FileOutputStream

檔案輸出位元組流,用於向檔案中寫入位元組。

4個常用建構函式:

FileOutputStream(String filePath)

FileOutputStream(File fileObj)

FileOutputStream(String filePath, boolean append)

FileOutputStream(File fileObj, boolean append)

在開始下面的例子前,我們先提到流關閉的一個細節,那就是

在JDK 7之前的遺留代碼,都使用顯式地調用close()方法來關閉流,這種辦法

比較笨拙。

老的代碼:

try {      FileOutputStream f0 = new FileOutputStream("file1.txt");      // 檔案寫入操作      } catch(IOException e) {      System.out.println("An I/O Error Occurred");    } finally {      try {        if(f0 != null) f0.close();      } catch(IOException e) {        System.out.println("Error Closing file1.txt");      }    }}

新的代碼(JDK 7及以後的代碼):

try (FileOutputStream f0 = new FileOutputStream("file1.txt")) {  // 檔案寫入操作  } catch(IOException e) {  System.out.println("An I/O Error Occurred");}

 是不是代碼變得更加簡潔了?

 

我們的例子:

package corejava8.io.stream;import java.io.*;public class FileOutputStreamDemo {    public static void main(String args[]) {        String source = "Now is the time for all good men\n" + " to come to the aid of their country\n"                + " and pay their due taxes.";        byte buf[] = source.getBytes();        // Use try-with-resources to close the files.        try (FileOutputStream f0 = new FileOutputStream("file1.txt");                FileOutputStream f1 = new FileOutputStream("file2.txt");                FileOutputStream f2 = new FileOutputStream("file3.txt")) {            // write to first file            for (int i = 0; i < buf.length; i++)                f0.write(buf[i]);                        // write to second file            f1.write(buf);                        // write to third file            f2.write(buf, 3, buf.length - 3);        } catch (IOException e) {            System.out.println("An I/O Error Occurred");        }    }}

運行結果如下:

第一個,第二個檔案內容都是:

Now is the time for all good men
to come to the aid of their country
and pay their due taxes.

第三個檔案跳過第一個單詞,內容如下:

is the time for all good men
to come to the aid of their country
and pay their due taxes.

上述代碼中:

byte buf[] = source.getBytes();

用於擷取來源資料(字串)的位元組數組。

 

Core Java - 流(Stream) - 位元組流和字元流(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.