流习题及思考题- 首都师范大学精品课程网(2)

2019-04-22 16:08

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); }


流习题及思考题- 首都师范大学精品课程网(2).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:应急排水泵管理制度

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: