就IO操作而言主要有3个大类:1是对字节的操作,2是对字符的操作,3是对对象的操作!
1对字节的操作有2个父类,inputstream outputstream
2对字符的操作有2个父类,Reader Writer
3是对象的操作有2个父类,ObjectInputStream ObjectOutputStream
首先先说最基础的字节操作类;
最常用的2个子类就是FileInputStream和 FileOutputStream;这两个类可以直接对文件进行读写操作;看见一个类,首先想其构造方法 .就InputStream和OutPutStream来说 最常用的构造方法就是FileInputStream fis=newFileInputStream("路径Sring");FileOutputStream fos=new FileOutputStream("路径");注意使用这个构造方法如果文件不存在,会自动创建一个文件.
就字节类来说,有2个重要的方法,一个是(int)fis.read();可以以字节的形式读取文件,当没有字节时返回-1;这样我们要遍历一个文件通常就用while(fis.read!=-1){fis.read();},fos.write()是fis.read的相反操作,往文件里写字节格式的内容;fos.flush()是刷新操作,fis.close(),fos.close()是关闭方法,这里会大量运用到异常的处理;注意.close()方法一般写在try-catch-finally的finally里面~;
下面看个例子:
public class FileOutputSteamDemo {
public static void main(String args[]){
//要操作的文件
File file = new File("g:"+File.separator+"outputstremdemo.txt");
//声明字节输出流
OutputStream outputStream = null;
try {
//通过子类实例化
outputStream = new FileOutputStream(file);
//当为true表示可以追加
outputStream = new FileOutputStream(file,true);
//要输出的信息
String str = "this is a OutputStream demo "+"\r\n";
//将String变为byte数组
byte b[] = str.getBytes();
//写入数据
outputStream.write(b);
//关闭
outputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
然后讲了字符和对象的操作,其实这两个类都是为了方便我们操作而封装的. 8bit=1byte
可以用记事本打开的文件都是字符文件
RreaderWriter最常用的两个子类是BufferedReader BufferedWriter;这两个子类有很好用的方法.readline();
要用以个类的方法必须先实例化这个类,这里有点特殊,BufferedReader和 FileInputStream建立联系必须有个中间的桥梁,这个桥梁就是InputStreamReader;
一般实现方式为
FileInputStream fis=null; InputStreamReader is=null;
BufferedReader br=null;
FileOutputStream fos=null;
try {
fis=new FileInputStream("e:/1.txt");
is=new InputStreamReader(fis);
br=new BufferedReader(is);
String str=null;
while((str=br.readLine())!=null){
System.out.println(str);
}
这样在FileInputStream上又搭建了一层字符流,可以进行很方便的操作。
最后讲了对象的操作,对对象的输入与输出又称为序列化和反序列化,如果想执行对象的序列化合反序列化,那么类必须实现Serializable这个接口。个人理解为自定义的类实现这个接口,而用java的类本身已经实现了这个接口。
一般的:
FileInputStream fis=null; ObjectInputStream ois=null;
FileOutputStream fos=null;
ObjectOutputStream oos=null;
File file=null;
try {
fos=new FileOutputStream("d:/test/stu.dat");
oos=new ObjectOutputStream(fos);
}
来使用它们,这里2者都有Stream所以不用中间人。
注意方法ois.readObject(),返回一个object对象,而oos.writeObject()传入一个对象的变量引用.
如果一个对象的属性不想被写入到文件,那么该属性使用关键字transient,注意属性的值不被序列化,变成初始值.