Java學習筆記之 IO包 位元組流

來源:互聯網
上載者:User

標籤:分行符號   stream   b2c   edit   demo   讀取   .net   抽象類別   text   

IO包最重要的五個類和一個介面

File/OutputStream/InputStream(位元組流)/Writer/Reader(字元流)

一個介面:Serializable

?

File類:



位元組流:

OutputStream與InputStream是抽象類別

OutputStream是整個IO包中。位元組輸出資料流的最大類

FileOutputStream是一個子類,通經常使用整個子類通過多態執行個體化OutputStream

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ29vZGh1YWp1bg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" />

?


?

?


packageiotest;

?

importjava.io.File;

importjava.io.FileNotFoundException;

importjava.io.IOException;

importjava.io.OutputStream;

importjava.io.FileOutputStream;

importjava.io.InputStream;

importjava.io.FileInputStream;

?

publicclass OutputStreamDemo1 {

public static void main(String args[]) throws Exception{

File f =newFile("D:"+File.separator+"javasrc"+File.separator+"write_file.txt");

OutputStream o=null;

o=new FileOutputStream(f);

String s="Hello World!";

byte b[]=s.getBytes();

o.write(b);

o.close();

//改動檔案 追加檔案內容

OutputStream o1=null;

o1=new FileOutputStream(f,true);

o1.write("\r\n".getBytes()); //添加分行符號

o1.write(b);

o1.close();

?

//讀取並列印檔案

//01 定義一個位元組數組 長度為1024

InputStream in1=null;

in1=new FileInputStream(f);

byte b1[]=new byte[1024];

int len=in1.read(b1);

in1.close();????????????????

print(b1,len);

?

//02 定義一個位元組數組 長度為檔案長度

InputStream in2=null;

in2=new FileInputStream(f);

byte b2[]=new byte[(int)f.length()];

in2.read(b2);

in2.close();

print(b2);

?

?? ????//03 已經檔案長度 逐個位元組讀取

?????????????InputStream in3=null;

in3=new FileInputStream(f);

byte b3[]=new byte[(int)f.length()];

for (int i=0;i<b3.length;i++){

b3[i]=(byte) in3.read();

}

in3.close();

print("the third read method:");

print(b3);

?????

//04 未知檔案長度讀取

InputStream in4=null;

in4=new FileInputStream(f);

byte b4[]=new byte[1024];

int i=0;

int temp=0;

while ((temp=in4.read())!=-1){

b4[i]=(byte)temp;

i++;

}

in4.close();

print("the fourth read method:");

print(b4);

}

?

public static void print(byte b[],int len){

System.out.println(new String(b,0,len));

}

public static void print(byte b[]){

System.out.println(new String(b));

}

public static void print(String b){

System.out.println(b);

}

?

}

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.