您的位置:首页 > 其它

IO流部分实例讲解

2012-12-30 21:49 218 查看
IO流部分:能够进行文件的简单读写操作,能够将文件的内容读取出来;会使用过滤流如BufferedInputStream的使用;了解装饰设计模式

BufferedReaderTest.java

package jsj.java.exam.test06;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BufferedReaderTest {
public static void main(String[] args) {
BufferedReader reader=null;
//创建缓冲输入流,接收从键盘中输入一行数据并进行输出显示
//要进行相应的异常处理
//注意关闭流
//reader=________061________
reader=new BufferedReader(new InputStreamReader(System.in));//2
System.out.println("请输入一行数据");
try {
String str=reader.readLine();//1
System.out.println("你输入的数据为:"+str);
} catch (IOException e) {//1
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}
ObjectInputStreamDemo .java

package jsj.java.exam.test06;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectInputStreamDemo {

/**
* @param args
* @throws IOException
* @throws FileNotFoundException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
File file=new File("d:"+File.separator+"person.txt");
ObjectInputStream ois=null;
ois=new ObjectInputStream(new FileInputStream(file));
//Object obj=________064________;//将对象恢复出来
Object obj=ois.readObject();//2
Person person=(Person)obj;
System.out.println(person);

}

}
ObjectOutputStreamDemo.java

package jsj.java.exam.test06;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ObjectOutputStreamDemo {

/**
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO Auto-generated method stub
File file=new File("d:"+File.separator+"person.txt");
ObjectOutputStream oos=null;
//创建对象输出流
//oos=________063________;//2
oos=new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(new Person("张三", 30));
oos.close();

}

}


person.java

package jsj.java.exam.test06;

import java.io.Serializable;

public class Person implements Serializable {
private String name;

//定义年龄属性,此属性不需要持久化保存
//________062________//2
private transient int age;

public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: