Java第八章 输入输出系统(基础篇)_第1页
Java第八章 输入输出系统(基础篇)_第2页
Java第八章 输入输出系统(基础篇)_第3页
Java第八章 输入输出系统(基础篇)_第4页
Java第八章 输入输出系统(基础篇)_第5页
已阅读5页,还剩41页未读 继续免费阅读

下载本文档

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

文档简介

1、第八章 输入/输出系统,流与文件 标准输入/输出 流输入/输出,6.1 流和文件,流:数据从计算机的输入向输出流动,即流的产生。 流有两种:文本流(字符)和二进制流(字节) 在JAVA里,流是一些类。 文件也是一个逻辑概念。计算机的所有设备都可理解为一个文件。流可与文件建立联系。(File),外部设备,输入流,计算机内部,输出流,外部设备,6.1 流和文件-常见流类,java.lang.Object java.io.File java.io.RandomAccessFile java.io.InputStream java.io.OutputStream java.io.Reader java

2、.io.Writer,6.2 标准输入/输出,标准输入输出属于系统类。系统类实现了用户使用资源时的系统无关编程接口:是最终类;所有变量和方法都是静态的;不用初始化(NEW)就可以使用 System.in public final static InputStream in = new InputStream(); read(),read(byte b,int off,int len),read(byte b) System.out public final static PrintStream out = new PrintStream(); print(),println(),write()

3、 System.err public final static PrintStream err = new PrintStream(); print(),println(),write(),6.2 标准输入/输出(例),import java.io.*; public class Count public static void main(String args) try int count = 0; while (System.in.read()!=-1) count+; System.out.println(input has+count+chars); catch(IOException

4、 e) System.err.println(Caught IOException:+e.toString(); ,6.3 文件File,创建一个新的文件对象 File(String pathname) File myFile = new File(etc/motd); File(String parent,String child) File myFile = new File(/etc , motd); File(File parent,String child) File myDir = new File(/etc ); File myFile = new File(myDir, mot

5、d);,6.3 文件File,File类提供的方法 文件名的操作(如) public String getName():返回文件对象名字符串; public String toString():返回文件名字符串; public String getParent():返回文件对象父路径名字符串; public File getParentFile():返回文件对象父文件名; public String getAbsolutePath():返回绝对路径名字符串; public static File createTempFile(String prefix, String suffix,File

6、directory) throws IOException public static File createNewFile() throws IOException,6.3 文件File,文件属性测试 public boolean canRead():是否能读指定的文件; public boolean canWrite():是否能修改指定的文件; public boolean exists():指定的文件是否存在; public boolean isDirectory():指定的文件是否是目录; public boolean isFile():指定的文件是否是一般文件; public boo

7、lean isHidden():指定的文件是否是隐藏文件; public boolean isAbsolute():指定的文件是否是绝对路径;,6.3 文件File,一般文件信息和工具 public long lastModified():返回文件最后被修改的时间; public long length():返回文件的字节长度; public boolean delete():删除指定的文件,若为目录必须为空才能删除; public void deleteOnExit():当虚拟机执行结束时,删除指定文件或目录;,6.3 文件File,目录操作 public boolean mkdir():创

8、建指定的目录; public boolean mkdirs():创建指定的目录,包括任何不存在的父目录; public String list():返回指定目录下的文件; public String list(FilenameFilter filter):返回指定目录下满足文件过滤器的文件;,6.3 文件File,文件属性设置 public boolean setLastModified(long time):设置指定目录或文件的最后修改时间; public boolean setReadOnly():设置指定目录或文件的只读属性;,6.3 文件File,其他 public URL toURL

9、() throws MalformedURLException:将相对路径名存入URL文件; public int compareTo(Object o):与另一个对象比较名字; public boolean equals(Object obj):与另一个对象比较名字; public int hashCode():返回文件名的哈希码;,6.3 文件File例,/ FileTest.java import java.io.*; public class FileTest public static void main( String args ) if(args.length0) for (in

10、t i=0;iargs.length;i+) File fileToTest = new File(argsi); info(fileToTest); elseSystem.out.println(“ No file given. ” ); ,6.3 文件File例,public static void info( File f ) try if ( f.exists() ) System.out.println( f.getName() + exists ); System.out.println( Last modified: + f.lastModified() ); System.ou

11、t.println( Length: + f.length() )” System.out.println(Path: + f.getPath() ); System.out.println(Absolute path: + f.getAbsolutePath(); System.out.println(Parent: + f.getParent() );,6.3 文件File例,System.out.println(“Can Write: f.canWrite() ); elseSystem.out.println( File does not exist ) catch(Exception

12、 e) System.out.println(e.toString(); ,6.4 字节输入流InputStream,字节输入流的方法 public abstract int read() throws IOException; public int read(byte b) throws IOException; public int read(byte b,int off,int len) throws IOException; public long skip(long n) throws IOException; public int available() throws IOExce

13、ption; public void close() throws IOException; public void mark(int readlimit); public void reset() throws IOException; public boolean markSupported() ;,6.4 字节输入流InputStream,java.lang.ObjectFileInputStream:读文件的流 PipedInputStream:内部线程通信的输入流 ByteArrayInputStream:读字节数组 java.io.InputStream SequenceInput

14、Stream:合并输入流的输入流 (抽象类) StringBufferInputStream:读字符串 FilterInputStream:读数据时处理数据(抽) BufferedInputStream:基本缓冲 DataInputStream:原始数据类型 LineNumberInputStream:支持行数字 PushBackInputStream:读完允许放回 AudioInputStream:输入音频数据 ObjectInputStream:直接进行对象的读,6.4 字节输入流InputStream,FileInputStream 重写父类中方法: public int read()

15、throws IOException; public int read(byte b) throws IOException; public int read(byte b,int off,int len) throws IOException; public long skip(long n) throws IOException; public int available() throws IOException; public void close() throws IOException; 重写Object类中方法: protected void finalize() throws I

16、OException; 自己定义方法: public final FileDescriptor getFD() throws IOException; 不支持mark(), reset();,6.4 字节输入流InputStream,FileInputStream 建立字节文件输入流: FileInputStream myFileStream = new FileInputStream(”etc/motd”); File myFile = new File(”etc/motd”); FileInputStream myFileStream = new FileInputStream( myFi

17、le); 关闭字节文件输入流: myFileStream.close();,6.4 字节输入流InputStream,BufferedInputStream 建立字节缓冲输入流: FileInputStream myFileStream = new FileInputStream(”etc/motd”); BufferedInputStream myBufferStream = new BufferedInputStream(myFileStream);,6.4 字节输入流InputStream,DataInputStream: 直接读取任意一种变量类型,如浮点数,整数,字符等 public

18、DataInputStream(InputStream in) public final char readChar() throws IOException; public final int readInt() throws IOException; public final Float readFloat() throws IOException; FileInputStream fis = new FileInputStream(”etc/motd”); DataInputStream dis = new DataInputStream(fis); int i = fis.read(b

19、); int j = dis.readInt(); dis.close(); fis.close();,6.5 字节输出流OutputStream,输 出字节流的方法 public abstract void write(int b) throws IOException; public void write(byte b) throws IOException; public void write(byte b,int off,int len) throws IOException; public void flush() throws IOException; public void cl

20、ose() throws IOException;,6.5 字节输出流OutputStream,java.lang.Object FileOutputStream:写文件的流 PipedOutputStream:内部线程输出流 ByteArrayOutputStream:写字节数组 java.io.OutputStream FilterOutputStream:写数据时处理 (抽象类) BufferedOutputStream:基本缓冲 DataOutputStream:原始数据类型 PrintStream:显示文本的输出流 ObjectOutputStream:直接写对象的流,6.5 字节输

21、出流OutputStream,FileOutputStream输 出字节流 重写父类中方法: public abstract void write(int b) throws IOException; public void write(byte b) throws IOException; public void write(byte b,int off,int len) throws IOException; public void close() throws IOException; 重写Object类中方法: protected void finalize() throws IOEx

22、ception; 自己定义方法: public final FileDescriptor getFD() throws IOException;,6.5 字节输出流OutputStream,FileOutputStream输 出字节流 建立字节文件输出流: FileOutputStream myFileStream = new FileOutputStream(”etc/motd”); File myFile = new File(”etc/motd”); FileOutputStream myFileStream = new FileOutputStream( myFile); 关闭字节文件

23、输入流:myFileStream.close();,6.5 字节输出流OutputStream,输入字节流(例) FileInputStream myFileStream = FileInputStream(“/usr/db/stock.dbf”); BufferedInputStream myBufferStream = BufferedInputStream(myFileStream); DataInputStream myDataStream = DataInputStream(myBufferStream); myFileStream.read(b); myBufferStream.r

24、ead(b); i = myDataStream.readInt(); myDataStream.close(); myBufferStream.close(); myFileStream.close();,6.5 字节输出流OutputStream,输 出字节流(例) FileOutputStream myFileStream = FileOutputStream(“/usr/db/stock.dbf”); BufferedOutputStream myBufferStream = BufferedOutputStream(myFileStream); DataOutputStream my

25、DataStream = DataOutputStream(myBufferStream); myFileStream.write(b); myBufferStream.write(b); myDataStream.writeInt(i); myDataStream.close(); myBufferStream.close(); myFileStream.close();,6.5 字节输出流OutputStream-FileInputStream和FileOutputStream例,import java.io.*; class FileStreamApp public static voi

26、d main(String Args) byte buffer = new byte2056; tryFileInputStream fis = new FileInputStream(einput.txt); FileOutputStream fos = new FileOutputStream(eoutput.txt); int bytes = fis.read(buffer) ; fos.write(buffer,0,bytes );fis.close();fos.close(); catch(Exception e) System.err.println(e.toString(); ,

27、6.6 接口和对象串行化,接口DataInput 接口DataOutput 接口Serializable和对象串行化(Serialization),6.6 接口和对象串行化,接口DataInput:从流中读取基本数据类型、读取一行数据、读取指定长度的字节。 Readfully(byte b)、readFully(byte b,int off,int len)、skipBytes(int n)、readBoolean()、readByte()、int readUnsignedByte()、readShort()、int readUnsignedShort()、readChar()、readInt

28、()、readLong()、readFloat()、readDouble()、String readLine()、String readUTF(),6.6 接口和对象串行化,接口DataInput,ObjectInputStream,DataInputStream,ObjectInput,DataInput,RandomAccessFile,6.6 接口和对象串行化,接口DataOutput:向流中写入基本数据类型、或写入指定长度的字节数组。 write(int b)、 write(byte b)、 write(byte b,int off,int len)、write Boolean(boo

29、lean v)、 writeByte(int v)、writeShort(int v)、writeChar(int v)、 writeInt(int v)、 writeLong(long v)、 writeFloat(float v)、 writeDouble(double v)、 writeBytes(String s)、writeChars(String s)、writeUTF(String s),6.6 接口和对象串行化,接口DataOutput,ObjectOutputStream,DataOutputStream,ObjectOutput,DataOutput,RandomAcces

30、sFile,6.6 接口和对象串行化,接口Serializable和对象串行化(Serialization) 接口Serializable Public interface Serializable; 对象串行化 概念:对象通过写出描述自己的状态的数值来记录自己的过程叫对象串行化。 目的:支持Java的对象持续性,支持对象的远程方法调用(RMI),支持扩充和定制。 任务:写出对象实例变量的数值。如果变量是另一个对象的引用,则引用的对象也要串行化。 方法:只有实现了Serializable接口的类的对象才可以被串行化;该对象必须与一定的对象输入和输出流联系进行状态保存和状态恢复。,6.6 接口和

31、对象串行化,接口Serializable和对象串行化(Serialization) 对象串行化 注意事项:串行化只能保存对象的实例成员变量的值;状态瞬时的对象不能串行化,保密的字段应加transient关键字。 定制串行化:默认的串行化机制,按照名称的升序写入其数值,如果想控制这些数值的写入顺序和写入类型,必须自己定义读写数据流的方式。,6.6 接口和对象串行化,/Student.java import java.io.*; public class Student implements Serializable int id; String name; int age; String dep

32、artment; public Student(int id,String name,int age,String department) this.id = id; = name; this.age = age; this.department = department;,6.6 接口和对象串行化,private void writeObject(ObjectOutputStream out) throws IOException out.writeInt(id); out.writeInt(age); out.writeUTF(name); out.writeUTF(d

33、epartment); private void readObject(ObjectInputStream in) throws IOException id = in.readInt(); age = in.readInt(); name = in.readUTF(); department = in.readUTF();,6.6 接口和对象串行化,/Objectser.java import java.io.*; public class Objectser public static void main(String args) throws IOException,ClassNotFo

34、undException Student stu = new Student(20031010, liming ,20, CEIC); FileOutputStream fout = new FileOutputStream(data.ser); ObjectOutputStream sout = new ObjectOutputStream(fout); trysout.writeObject(stu); sout.close();catch(IOException e) System.out.println(e.toString();,6.6 接口和对象串行化,stu = null; Fi

35、leInputStream fin = new FileInputStream(data.ser); ObjectInputStream sin = new ObjectInputStream(fin); try stu = (Student)sin.readObject(); sin.close();catch(IOException e) System.out.println(e.toString(); System.out.println(Student info:); System.out.println(ID :+stu.id); System.out.println(Name:+s

36、); System.out.println(Age:+stu.age); System.out.println(Dep.:+stu.department);,6.7 随机存取文件RandomAccessFile,构造方法 RandomAccessFile(String name,String mode) RandomAccessFile(File file,String mode) 使用方法 接口DataInput 接口DataOutput getFilePointer():返回当前文件指针位置; Seek(long pos):把文件指针定位于pos的位置; Length():得到文件的长度.,6.8 字符类输入流Reader,java.la

温馨提示

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

评论

0/150

提交评论