(1)节点流
PrintWriter ps=new PrintWriter("demo.txt","utf-8");
上下两个等价
File f=new File("demo.txt");
PrintWriter ps=new PrintWriter(f,"gbk");
(2)处理流
FileWriter fw=new FileWriter("demo.txt");
PrintWriter pw=new PrintWriter(fw,true); [ println() printf() format()]
字节流可以指定编码方式,处理流可以指定自动刷新
既想指定编码方式又想指定自动刷新:
OutputStreamWriter ow=new OutputStreamWriter(new FileOutputStream(“demo.txt”),“utf-8”);//转换的字符的输出流
PrintWriter pw1=new PrintWriter(ow,true);
12.6对象序列化
序列化(Serialization)是指把并行数据转换成字符串行数据的处理过程,而对象序列化(Object Serialization)是指把对象的状态数据以字节流的形式进行处理,一般用于实现完全的对象。
实现对象序列化:
//向文件中写入对象数据
FileOutputStream fos=new FileOutStream(“obj.dat”);
ObjectOutputStream oos=new ObjectOutputStram(fos);
oos.writeObject(new Person(“张三”,20));
oos.writeObject(new Person(“李四”,21));
oos.close();
//从文件中读取对象数据
FileInputStream fis=new FileInputStream(“obj.dat”);
ObjectInputStream ois=new ObjectInputStream(fis);
运行程序ObjectStream.java以对象为单位将Person类型的数据写入到数据文件obj.dat中,然后以对象为单位读取文件数据。
不是任何引用类型的数据对象都可以进行序列化、持久化,要想序列化,要是新一个串行化的接口Serializable,这个接口在java.io包下,实现之后可以串行化,实际是一个空接口,是一个标志
public class DemoObjectStream implements Serializable{
public static void main(String[] args) throws IOException, ClassNotFoundException {
//将几个对象持久化到磁盘文件中
Employee e1=new Employee("张三",25,"开发部");
Employee e2=new Employee("李四",30,"市场部");
e1.setCount(200);
System.out.println(e2.getCount());
//对象流,构建对象的输出流
FileOutputStream fos=new FileOutputStream("obj.dat");//文件字节的输出流连接到数据源上
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(e1);//对象的序列化过程
oos.writeObject(e2);
oos.close();
//读取出来,反序列化
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("obj.dat"));
Employee e3=(Employee) ois.readObject();
Employee e4=(Employee) ois.readObject();
System.out.println(e3.toString());
System.out.println(e4.toString());
System.out.println(e3.getCount());
ois.close();
}
}
private static int count=100;//静态成员不会被序列化
private transient int age;//加关键字transient修饰的非静态成员也是不被序列化的
SequenceInputStream 将几个输入流合并成一个流
ArrayList<FileInputStream > al = new ArrayList<FileInputStream>();
for(int x=1; x<4; x++)
al.add(new FileInputStream(x+".txt"));
final Iterator<FileInputStream> it = al.iterator();
//匿名类
Enumeration<FileInputStream> en = new Enumeration<FileInputStream>()
{
public boolean hasMoreElements(){
return it.hasNext();
}
public FileInputStream nextElement(){
return it.next();
}
};
//多个流就变成了一个流,这就是数据源。
SequenceInputStream sis = new SequenceInputStream(en);
//创建数据目的。
FileOutputStream fos = new FileOutputStream("4.txt");
byte[] buf = new byte[1024*4];
int len = 0;
while((len=sis.read(buf))!=-1){
fos.write(buf,0,len);
}
fos.close();sis.close();
//如果要一个对文件数据切割。
一个读取对应多了输出。
FileInputStream fis = new FileInputStream("1.mp3");
FileOutputStream fos = null;
byte[] buf = new byte[1024*1024];//是一个1m的缓冲区。
int len = 0;
int count = 1;
while((len=fis.read(buf))!=-1){
fos = new FileOutputStream((count++)+".part");
fos.write(buf,0,len);
fos.close();
}
fis.close();