java中IO流相關知識點

來源:互聯網
上載者:User

標籤:內容   ati   void   print   分隔字元   imp   知識點   str   exception   

package zdbIO;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class OutputStreamDemo1 {

    /**
     * @throws IOException
     * @throws IOException
     *
     */

 

  下邊使用outputStream位元組輸出資料流進行寫操作


    public static void main(String[] args) throws IOException{
        
        /**
         * 使用IO流的具體步驟:
         *             1.使用file找到要操作的檔案
         *             2.(使用位元組流或字元流的子類來執行個體化inputStream、outStream、reader、writer)
         *             3.進行讀寫操作
         *             4.關閉流,除BufferedReader例外
         */
        
        File file = new File("f:"+File.separator+"zdb1.txt");//使用file找到要操作的檔案
        OutputStream out = null;
        out = new FileOutputStream(file,true);//使用OutputStream的子類進行執行個體化
        String str = "XXX的十年人生規劃,一定要有個計劃這樣你的人生才會有明確的方向 不至於迷失。";//要輸出的資訊
        byte b[] = str.getBytes();//將str變為byte數組
        out.write(b);//寫入資料
        out.close();//關閉流
        
    }
    
}

下邊使用inputStream位元組流進行讀操作:


package zdbIO;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 通過inputStream位元組流來進行讀操作
 *
 */
public class InputStreamDemo {
    public static void main(String[] args) throws Exception {
        //注意此檔案必須存在否則會發生java.io.FileNotFoundException異常
        //File.separator表示分隔字元,其中在Windows中表示\,在unix表示/,這樣可以跨平台
        File file = new File("f:"+File.separator+"zdb1.txt");
        InputStream input = null;
        input = new FileInputStream(file);
        byte b[] = new byte[1024];//開闢一塊記憶體用來儲存讀取的內容
        int len = input.read(b);//將檔案讀到字元數組中
        //其中new String(byte[]bytes,int offset,int length),
        //表示將建立一個字串,從offset為開始,長度為length
        System.out.println(new String(b,0,len));
        input.close();
        
    }

}






















































 

java中IO流相關知識點

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.