String desc;
double total = 0.0; try { //利用数据输入流读文件内容 while (true) {
price = in.readDouble();
in.readChar(); // throws out the tab unit = in.readInt();
in.readChar(); // throws out the tab desc = in.readLine();
System.out.println(\ unit + \ desc + \ total = total + unit * price; } } //捕获异常 catch (EOFException e) { e.printStackTrace(); }
System.out.println(\ //关闭数据输入流 in.close(); } }
8、利用BufferedReader和BufferedWriter在文件中实现输入输出字符串。 import java.io.*;
public class ko24_6 {
public static void main(String args[]) throws IOException {
String line; String str=\ BufferedWriter kow=new BufferedWriter(new FileWriter(\ kow.write(str,0,str.length()); kow.flush(); BufferedReader kor=new BufferedReader(new FileReader(\ line=kor.readLine(); System.out.println(line); } }
9、什么是过滤流,并举例
解:过滤流在读/写数据的同时可以对数据进行处理,它提供了同步机制,使得某一时刻只有一个线程可以访问一个I/O流,以防止多个线程同时对一个I/O流进行操作所带来的意想不到的结果。类FilterInputStream和FilterOutputStream分别作为所有过滤输入流和输出流的父类。
为了使用一个过滤流,必须首先把过滤流连接到某个输入/出流上,通常通过在构造方法的参数中指定所要连接的输入/出流来实现。例如:
FilterInputStream( InputStream in ); FilterOutputStream( OutputStream out ); 下面的类均是过滤流的例子
BufferedInputStream和BufferedOutputStream
缓冲流,用于提高输入/输出处理的效率。 DataInputStream 和 DataOutputStream
不仅能读/写数据流,而且能读/写各种的java语言的基本类型,如:boolean,int,float等。
LineNumberInputStream
除了提供对输入处理的支持外,LineNumberInputStream可以记录当前的行号。 PushbackInputStream
提供了一个方法可以把刚读过的字节退回到输入流中,以便重新再读一遍。 PrintStream
打印流的作用是把Java语言的内构类型以其字符表示形式送到相应的输出流。
10、什么是串行化,并举例
解:对象的寿命通常随着生成该对象的程序的终止而终止。有时候,可能需要将对象的状态保存下来,在需要时再将对象恢复。我们把对象的这种能记录自己的状态以便将来再生的能力,叫做对象的持续性(persistence)。对象通过写出描述自己状态的数值来记录自己,这个过程叫对象的串行化(Serialization)。
串行化的目的是为java的运行环境提供一组特性,其主要任务是写出对象实例变量的数值。
首先定义一个可串行化对象
public class Student implements Serializable{ int id; //学号
String name; //姓名 int age; //年龄
String department //系别
public Student(int id,String name,int age,String department){ this.id = id;
this.name = name; this.age = age;
this.department = department; } }
其次是构造对象的输入/输出流 java.io包中,提供了ObjectInputStream和ObjectOutputStream将数据流功能扩展至可读写对象。在ObjectInputStream中用readObject()方法可以直接读取一个对象,ObjectOutputStream中用writeObject()方法可以直接将对象保存到输出流中。 Student stu=new Student(981036,\ FileOutputStream fo=new FileOutputStream(\ //保存对象的状态
ObjectOutputStream so=new ObjectOutputStream(fo); try{
so.writeObject(stu); so.close();
}catch(IOException e )
{System.out.println(e);}
FileInputStream fi=new FileInputStream(\ ObjectInputStream si=new ObjectInputStream(fi); //恢复对象的状态 try{
stu=(Student)si.readObject(); si.close();
}catch(IOException e ) {System.out.println(e); }