java中输入输出学习文档_第1页
java中输入输出学习文档_第2页
java中输入输出学习文档_第3页
java中输入输出学习文档_第4页
java中输入输出学习文档_第5页
已阅读5页,还剩15页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

java 中输入输出的总括中输入输出的总括 初学必看初学必看 第八章 输入输出流 课前思考 1 字节流和字符流的基类各是什么 2 什么是对象的串行化 对象串行化的作用是什么 学习目标 本讲主要讲述了 java 语言中的输入 输出的处理 通过本讲的学习 同学们可以编写更为完 善的 java 程序 学习指南 仔细阅读本章各知识点的内容 深刻理解 java 语言中输入 输出流的处理方法 掌握处理问 题的方法 多练习 多上机 难 重 点 遇到实际问题时 要根据需要正确使用各种输入 输出流 特别是对中文使用适当的字 符输入流 正确使用对象串行化的方法 处理字符流时 其构造方法的参数是一个字节流 对象串行化的概念 知 识 点 I O 流概述 文件处理 过滤流 字符流的处理 对象的串行化 其它常用的流 内 容 第一节 数据流的基本概念 理解数据流 流一般分为输入流 Input Stream 和输出流 Output Stream 两类 但这种划分并不是绝 对的 比如一个文件 当向其中写数据时 它就是一个输出流 当从其中读取数据时 它 就是一个输入流 当然 键盘只是一个数人流 而屏幕则只是一个输出流 Java 的标准数据流 标准输入输出指在字符方式下 如 DOS 程序与系统进行交互的方式 分为三种 标准输入 studin 对象是键盘 标准输出 stdout 对象是屏幕 标准错误输出 stderr 对象也是屏幕 例 8 1 从键盘输入字符 本例用 System in read buffer 从键盘输入一行字符 存储在缓冲区 buffer 中 count 保存实 际读入的字节个数 再以整数和字符两种方式输出 buffer 中的值 Read 方法在 java io 包中 而且要抛出 IOException 异常 程序如下 import java io public class Input1 public static void main String args throws IOException System out println Input byte buffer new byte 512 输入缓冲区 int count System in read buffer 读取标准输入流 System out println Output for int i 0 i COUNT I 输出 buffer 元素值 System out print buffer i System out println for int i 0 i0 读取输入流 System out print new String buffer System out println rf close 关闭输入流 catch IOException ioe System out println ioe catch Exception e System out println e 例 8 3 写入文件 本例用 System in read buffer 从键盘输入一行字符 存储在缓冲区 buffer 中 再以 FileOutStream 的 write buffer 方法 将 buffer 中内容写入文件 Write1 txt 中 程序如下 import java io public class Write1 public static void main String args try System out print Input int count n 512 byte buffer new byte n count System in read buffer 读取标准输入流 FileOutputStream wf new FileOutputStream Write1 txt 创建文件输出流对象 wf write buffer 0 count 写入输出流 wf close 关闭输出流 System out println Save to Write1 txt catch IOException ioe System out println ioe catch Exception e System out println e 第三节 文件操作 File 类 File 类声明如下 public class File ectends Object implements Serializable Comparable 构造方法 public File String pathname public File File patent String chile public File String patent String child 文件名的处理 String getName 得到 一个文件的名称 不包括路径 String getPath 得到一个文件的路径名 String getAbsolutePath 得到一个文件的绝对路径名 String getParent 得到一个文件的上一级目录名 String renameTo File newName 将当前文件名更名为给定文件的完整路径 文件属性测试 boolean exists 测试当前 File 对象所指示的文件是否存在 boolean canWrite 测试当前文件是否可写 boolean canRead 测试当前文件是否可读 boolean isFile 测试当前文件是否是文件 不是目录 boolean isDirectory 测试当前文件是否是目录 普通文件信息和工具 long lastModified 得到文件最近一次修改的时间 long length 得到文件的长度 以字节为单位 boolean delete 删除当前文件 目录操作 boolean mkdir 根据当前对象生成一个由该对象指定的路径 String list 列出当前目录下的文件 例 8 4 自动更新文件 本例使用 File 类对象对指定文件进行自动更新的操作 程序如下 import java io import java util Date import java text SimpleDateFormat public class UpdateFile public static void main String args throws IOException String fname Write1 txt 待复制的文件名 String childdir backup 子目录名 new UpdateFile update fname childdir public void update String fname String childdir throws IOException File f1 f2 child f1 new File fname 当前目录中创建文件对象 f1 child new File childdir 当前目录中创建文件对象 child if f1 exists if child exists child 不存在时创建子目录 child mkdir f2 new File child fname 在子目录 child 中创建文件 f2 if f2 exists f2 不存在时或存在但日期较早时 f2 exists 复制 getinfo f1 getinfo child else System out println f1 getName file not found public void copy File f1 File f2 throws IOException 创建文件输入流对象 FileInputStream rf new FileInputStream f1 FileOutputStream wf new FileOutputStream f2 创建文件输出流对象 int count n 512 byte buffer new byte n count rf read buffer 0 n 读取输入流 while count 1 wf write buffer 0 count 写入输出流 count rf read buffer 0 n System out println CopyFile f2 getName rf close 关闭输入流 wf close 关闭输出流 public static void getinfo File f1 throws IOException SimpleDateFormat sdf sdf new SimpleDateFormat yyyy 年 MM 月 dd 日 hh 时 mm 分 if f1 isFile System out println t f1 getAbsolutePath t f1 length t sdf format new Date f1 lastModified else System out println t f1 getAbsolutePath File files f1 listFiles for int i 0 i FILES LENGTH I getinfo files i f1 lastModified 返回一个表示日期的长整型 值为从 1970 年 1 月 1 日零时开始计 算的毫秒数 并以此长整型构造一个日期对象 再按指定格式输出日期 程序运行 结果如下 D myjava Write1 txt 6 2002 年 12 月 11 日 02 时 18 分 D myjava backup D myjava backup Write1 txt 6 2002 年 12 月 31 日 05 时 13 分 文件过滤器 类 FilterInputStream 和 FilterOutputStream 分别对其他输入 输出流进行特殊 处理 它们在读 写数据的同时可以对数据进行特殊处理 另外还提供了同 步机制 使得某一时刻只有一个线程可以访问一个输入 输出流 类 FilterInputStream 和 FilterOutputStream 分别重写了父类 InputStream 和 OutputStream 的所有方法 同时 它们的子类也应该重写它们的方法以满 足特定的需要 要使用过滤流 首先必须把它连接到某个输入 输出流上 通常在构造 方法的参数中指定所要连接的流 FilterInputStream InputStream in FilterOutputStream OutputStream out 这两个类是抽象类 构造方法也是保护方法 类 BufferedInputStream 和 BufferedOutputStream 实现了带缓冲的过滤流 它 提供了缓冲机制 把任意的 I O 流 捆绑 到缓冲流上 可以提高读写效率 在初始化时 除了要指定所连接的 I O 流之外 还可以指定缓冲区的大 小 缺省大小的缓冲区适合于通常的情形 最优的缓冲区大小常依赖于主 机操作系统 可使用的内存空间以及机器的配置等 一般缓冲区的大小为 内存页或磁盘块等地整数倍 如 8912 字节或更小 BufferedInputStream InputStream in int size BufferedOutputStream OutputStream out int size 例 8 5 列出当前目录中带过滤器的文件名清单 本例实现 FilenameFilter 接口中的 accept 方法 在当前目录中列出带过滤器 的文件名 程序如下 import java io public class DirFilter implements FilenameFilter private String prefix suffix 文件名的前缀 后缀 public DirFilter String filterstr filterstr filterstr toLowerCase int i filterstr indexOf int j filterstr indexOf if i 0 prefix filterstr substring 0 i if j 0 suffix filterstr substring j 1 public static void main String args 创建带通配符的文件名过滤器对象 FilenameFilter filter new DirFilter w abc txt File f1 new File File curdir new File f1 getAbsolutePath 当前目录 System out println curdir getAbsolutePath String str curdir list filter 列出带过滤器的文件名清单 for int i 0 i STR LENGTH I System out println t str i public boolean accept File dir String filename boolean yes true try filename filename toLowerCase yes filename startsWith prefix catch NullPointerException e return yes 程序运行时 列出当前目录中符合过滤条件 w txt 的文件名清单 结果如 下 D myjava Write1 txt Write2 txt 文件对话框 随机文件操作 于 InputStream 和 OutputStream 来说 它们的实例都是顺序访问流 也就 是说 只能对文件进行顺序地读 写 随机访问文件则允许对文件内容进行 随机读 写 在 java 中 类 RandomAccessFile 提供了随机访问文件的方法 类 RandomAccessFile 的声明为 public class RandomAccessFile extends Object implements DataInput DataOutput File 以文件路径名的形式代表一个文件 FileDescriptor 代表一个打开文件的文件描述 FileFilter public class PrimesFile RandomAccessFile raf public static void main String args throws IOException new PrimesFile createprime 100 public void createprime int max throws IOException raf new RandomAccessFile primes bin rw 创建文件对象 raf seek 0 文件指针为 0 raf writeInt 2 写入整型 int k 3 while k max if isPrime k raf writeInt k k k 2 output max raf close 关闭文件 public boolean isPrime int k throws IOException int i 0 j boolean yes true try raf seek 0 int count int raf length 4 返回文件字节长度 while i count else i raf seek i 4 移动文件指针 catch EOFException e 捕获到达文件尾异常 return yes public void output int max throws IOException try raf seek 0 System out println 2 max 中有 raf length 4 个素数 for int i 0 i int raf length 4 i raf seek i 4 System out print raf readInt if i 1 10 0 System out println catch EOFException e System out println 程序运行时创建文件 primes bin 并将素数写入其中 结果如下 2 100 中有 25 个素数 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 第四节 字符流 Reader 类和 Writer 类 前面说过 在 JDK1 1 之前 java io 包中的流只有普通的字节流 以 byte 为基本处 理单位的流 这种流对于以 16 位的 Unicode 码表示的字符流处理很不方便 从 JDK1 1 开始 java io 包中加入了专门用于字符流处理的类 它们是以 Reader 和 Writer 为基础派生的一系列类 同类 InputStream 和 OutputStream 一样 Reader 和 Writer 也是抽象类 只提供了一 系列用于字符流处理的接口 它们的方法与类 InputStream 和 OutputStream 类似 只不过其中的参数换成字符或字符数组 Reader 类 void close void mark int readAheadLimit boolean markSupported int read int read char cbuf int read char cbuf int off int len boolean ready void reset long skip long n Writer 类 void close void flush void write char cbuf void write char cbuf int off int len void write int c void write String str void write String str int off int len 例 8 7 文件编辑器 本例实现文件编辑器中的打开 保存文件功能 程序如下 import java awt import java awt event import java io public class EditFile1 extends WindowAdapter implements ActionListener TextListener Frame f TextArea ta1 Panel p1 TextField tf1 Button b1 b2 b3 FileDialog fd File file1 null public static void main String args new EditFile1 display public void display f new Frame EditFile f setSize 680 400 f setLocation 200 140 f setBackground Color lightGray f addWindowListener this tf1 new TextField tf1 setEnabled false tf1 setFont new Font Dialog 0 20 设置文本行的初始字体 f add tf1 North ta1 new TextArea ta1 setFont new Font Dialog 0 20 设置文本区的初始字体 f add ta1 ta1 addTextListener this 注册文本区的事件监听程序 p1 new Panel p1 setLayout new FlowLayout FlowLayout LEFT b1 new Button Open b2 new Button Save b3 new Button Save As p1 add b1 p1 add b2 p1 add b3 b2 setEnabled false b3 setEnabled false b1 addActionListener this 注册按钮的事件监听程序 b2 addActionListener this b3 addActionListener this f add p1 South f setVisible true public void textValueChanged TextEvent e 实现 TextListener 接口中的方法 对文本区操作时触发 b2 setEnabled true b3 setEnabled true public void actionPerformed ActionEvent e if e getSource b1 单击 打开 按钮时 fd new FileDialog f Open FileDialog LOAD fd setVisible true 创建并显示打开文件对话框 if fd getDirectory null try 以缓冲区方式读取文件内容 file1 new File fd getDirectory fd getFile FileReader fr new FileReader file1 BufferedReader br new BufferedReader fr String aline while aline br readLine null 按行读取文本 ta1 append aline r n fr close br close catch IOException ioe System out println ioe if e getSource b2 e getSource b3 单击 保存 按钮时 if e getSource b3 e getSource b2 if file1 null fd setFile Edit1 txt else fd setFile file1 getName fd setVisible true 创建并显示保存文件对话框 if fd getDirectory null file1 new File fd getDirectory fd getFile save file1 else save file1 public void save File file1 try 将文本区内容写入字符输出流 FileWriter fw new FileWriter file1 fw write ta1 getText fw close b2 setEnabled false b3 setEnabled false catch IOException ioe System out println ioe public void windowClosing WindowEvent e System exit 0 第五节 字节流的高级应用 管道流 管道用来把一个程序 线程和代码块的输出连接到另一个程序 线程和代码块的输入 java io 中提供了类 PipedInputStream 和 PipedOutputStream 作为管道的输入 输出流 管道输入流作为一个通信管道的接收端 管道输出流则作为发送端 管道流必须是输入输 出并用 即在使用管道前 两者必须进行连接 管道输入 输出流可以用两种方式进行连接 在构造方法中进行连接 PipedInputStream PipedOutputStream pos PipedOutputStream PipedInputStream pis 通过各自的 connect 方法连接 在类 PipedInputStream 中 connect PipedOutputStream pos 在类 PipedOutputStream 中 connect PipedInputStream pis 例 8 8 管道流 本例例管道流的使用方法 设输入管道 in 与输出管道 out 已连接 Send 线程向输出管道 out 发送数据 Receive 线程从输入管道 in 中接收数据 程序如下 import java io public class Pipedstream public static void main String args PipedInputStream in new PipedInputStream PipedOutputStream out new PipedOutputStream try in connect out catch IOException ioe Send s1 new Send out 1 Send s2 new Send out 2 Receive r1 new Receive in Receive r2 new Receive in s1 start s2 start r1 start r2 start class Send extends Thread 发送线程 PipedOutputStream out static int count 0 记录线程个数 int k 0 public Send PipedOutputStream out int k this out out this k k this count 线程个数加 1 public void run System out print r nSend this k this getName int i k try while i 10 out write i i 2 sleep 1 if Send count 1 只剩一个线程时 out close 关闭输入管道流 System out println out closed else this count 线程个数减 1 catch InterruptedException e catch IOException e class Receive extends Thread 接收线程 PipedInputStream in public Receive PipedInputStream in this in in public void run System out print r nReceive this getName try int i in read while i 1 输入流未结束时 System out print i i in read sleep 1 in close 关闭输入管道流 catch InterruptedException e catch IOException e System out println e 程序运行结果如下 Send1 Thread 0 Send2 Thread 1 Receive Thread 2 1 Receive Thread 3 2 3 4 5 7 out closed 6 8 9 java io IOException Pipe closed 数据流 DataInputStream 和 DataOutputStream 在提供了字节流的读写手段的同时 以统一的通用的形式向输入流中写入 boolean int long double 等基本数据类型 并可 以在次把基本数据类型的值读取回来 提供了字符串读写的手段 分别实现了 DataInput 和 DataOutput 接口 声明类 Public class DataInputStream extends filterInputStream implements DataInput 例 8 9 数据流 本例演示数据流的使用方法 程序如下 import java io public class Datastream public static void main String arg String fname student1 dat new Student1 Wang save fname new Student1 Li save fname Student1 display fname class Student1 static int count 0 int number 1 String name Student1 String n1 this count 编号自动加 1 this number this count this name n1 Student1 this void save String fname try 添加方式创建文件输出流 FileOutputStream fout new FileOutputStream fname true DataOutputStream dout new DataOutputStream fout dout writeInt this number dout writeChars this name n dout close catch IOException ioe static void display String fname try FileInputStream fin new FileInputStream fname DataInputStream din new DataInputStream fin int i din readInt while i 1 输入流未结束时 System out print i char ch while ch din readChar n 字符串未结束时 System out print ch System out println i din readInt din close catch IOException ioe 程序运行结果如下 1 Wang 2 Li 对象流 对象的持续性 Persistence 能够纪录自己的状态一边将来再生的能力 叫对象的持续性 对象的串行化 Serialization 对象通过写出描述自己状态的的数值来记录自己的过程叫串行化 串行化的主要任务 是写出对象实例变量的数值 如果变量是另一个对象的引用 则引用的对象也要串行化 这个过程是递归的 对象流 能够输入输出对象的流称为对象流 可以将对象串行化后通过对象输入输出流写入文件或传送到其它地方 在 java 中 允许可串行化的对象在通过对象流进行传输 只有实现 Serializable 接口的类才 能被串行化

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论