Cher ZY
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    :::info <a href="/@TFA101/CherryJava" target="_self"> < :notebook_with_decorative_cover: [共享目錄] Java 2 學習筆記</a> ::: # 模組7 循序存取媒體(I/O、Reader/Writer) 本筆記會提到的內容: * 輸入、輸出的基本概念 * 資料流API的架構 * 父類別常用的方法 * 操作低階(節點)資料流複製檔案的注意事項 ## 資料流處理觀念 輸入與輸出相關的類別會用到以下的單字,很好識別: | 輸入 | 輸出 | | ----- | ------ | | Input | Output | | Read | Write | 資料流的概念,就像是水流一般讀取一連串的資料。 * 輸入:資料由「源頭(Source)」流向程式。 * 輸出:資料由程式流向「目的地(Destination)」。 ## 資料流 就像水流方向由水管控制,資料流向由資料流類別控制,Java的資料流類別來自4個<font color="#f00">抽象</font>父類別。我們只需要使用已經實作好的子類別即可,不需要繼承和實作方法。 :::info 一般來說,抽象類別的特性:<div style="margin-bottom:6px;" title="保持間距用"></div>1. 不能建立物件。 2. 繼承的子類別繼承父類別需實作方法。 ::: ### 簡述低階資料流 直接與Source、Program相接的資料流稱為節點流,屬於低階的資料流,但仍然可以透過繼承自父類別(InputStream/OutputStream、Reader/Writer)的read、write功能完成資料的傳輸。 ### 簡述高階資料流 **高階資料流通常參與<font color="#f00">處理(加工)</font>資料的動作**,會有特殊的功能,如:緩衝區、資料型態轉換、字元編碼、更多讀寫方法等功能。 ## 輸入資料流 先寫在前面: 以下提到 `XxxInputStream` 或 `XxxOutputStream` 的 `Xxx`,視輸入/出的類型而定。 如Object物件的輸入/出即為 `ObjectInputStream` / `ObjectOutputStream`(另註:一般來說物件僅會以I/O方式傳輸)。 ### 以I/O來表示 :::warning I/O資料流以8 bits(即一個byte)為基礎傳輸,基本上任何資料都可以使用,網路I/O和Concole I/O(如:CMD)也以此為基礎。 ::: **唯獨處理Unicode字元(16 bits)會有拆字元而導致亂碼的問題。** 另外,此處的File表示File物件,可預先置入輸入路徑,不屬於資料流類別。 > *[Source]* → (File) → FileInputStream → BufferedInputStream → XxxInputStream → *[Program]* ### 以Read/Write來表示 > *[Source]* → (File) → FileReader → BufferedReader → XxxReader → *[Dest]* ## 輸出資料流 此處的File表示File物件,可預先置入輸出路徑,不屬於資料流類別。 ### 以I/O來表示 > *[Program]* → (File) → XxxOutputStream → BufferedOutputStream → FileOutputStream → *[Dest]* ### 以Read/Write來表示 > *[Program]* → (File) → XxxWriter → BufferedWriter → FileWriter → *[Dest]* ## 資料流父類別與其常用方法 ### 輸入父類別 #### InputStream * **int read()** 回傳值若為-1,則代表已到檔案末端。 * **int read(byte[] buf)** 一段資料長度為buf.length,讀取下一段資料並放入陣列buf中。範例[點此參考](http://tw.gitbook.net/java/io/inputstream_read_byte.html)。 回傳值為實際讀到的byte數量,若為-1,則代表已到檔案末端。 * **int read(byte[] buf, int offset, int length)** 一段資料長度為buf.length,讀取下一段資料並放入陣列buf中,並從offset當作起點。範例[點此參考](http://tw.gitbook.net/java/io/inputstream_read_byte_len.html),另還有[文字說明](https://stackoverflow.com/questions/18597244/java-does-inputsream-readbyte-b-int-offset-int-length-wait-for-the-full-am)。 回傳值為實際讀到的byte數量,若為-1,則代表已到檔案末端。 #### Reader * **int read()** * **int read(char[] cbuf)** * **int read(char[] cbuf, int offset, int length)** ### 輸出父類別 #### OutputStream * **void write(int b)** 將b位元組的資料寫至目的地。 * **void write(byte[] buf)** 將陣列buf裡所有的位元組資料寫至目的地。 * **void write(byte[] buf, int offset, int length)** 將陣列buf中從offset開始的length位元組資料寫至目的地。 #### Writer * **void write(int c)** * **void write(char[] cbuf)** * **void write(char[] cbuf, int offset, int length)** ## 複製檔案的資料流操作注意事項 資料流的流向,以Java Program當作中介,先將資料輸入於Program,再將其輸出。 ### 以I/O低階資料流作為範例 > *[Source]* → FileInputStream fis → **fis.read()** → Program → > FileOutputStream fos → fos.write() → *[Dest]* → 資料流的close動作(越晚建立,越早關閉) ### read(); 的條件檢測 輸入資料流,連低階的節點資料流最基本也會有繼承自父類別的 `read();` 方法可以用來輸入資料。 `read();` 每次讀取一個字元,所以需要設定迴圈,使讀取的動作可以重複執行,直到整個檔案的內容都可以被完整輸入。 方便的是,`read();` 的回傳數值可以讓我們知道接下來**是否仍有資料要讀取**,因此可以將回傳值作為while迴圈,作為執行條件: 1. 有,會回傳下一個字元的的數值(型別為int,為讀取字元的byte code,`(char)i` 強制轉型可以得到這個字元) 2. 沒有,則回傳 `-1`。 因此迴圈條件設為 `!= -1` 即可,搭配 `System.out.print();` 可以讓我們在螢幕上見到輸入的成果。 ### I/O 低階資料流輸入資料的範例 ```java=3 // 前略... int i; while( (i = fis.read()) != -1) { System.out.print(i); // 若寫為System.out.print((char)i); // 則直接轉為字元(仍需注意I/O僅能傳輸8 bits資料長度的問題) } ``` ### 高階資料流的迴圈條件與範例 高階資料流 BufferedInputStream 有特殊的輸入功能 `readLine();` 方法,能以「行」為單位進行輸入。要使用這個方法,需要透過 **BufferedInputStream 的物件來呼叫**,回傳值則為 String 型別。 `readLine();` 若讀取到 \r\n,則代表讀取已到檔案末端,將回傳null,所以在這裡應該要使用 `!=null`作為進入迴圈的條件。 ```java=3 // 前略... String s; while( (s = fis.readLine()) != null) { System.out.println(s); // 若寫為System.out.print(s); // 整行印出,就不需要轉成字元了 } ``` <!-- String自己會轉? --> :::warning 最後應該要注意的是,使用這個方法輸入,換行效果會被吃掉,需另外想辦法解決。 :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully