標籤:分行符號 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包 位元組流