IO包最重要的五个类和一个接口
File/OutputStream/InputStream(字节流)/Writer/Reader(字符流)
一个接口:Serializable
File类:
字节流:
OutputStream与InputStream是抽象类
OutputStream是整个IO包中。字节输出流的最大类
FileOutputStream是一个子类,通经常使用整个子类通过多态实例化OutputStream
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(" ".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);
}
}