java输入输出流

来源:互联网 发布:云计算hcie待遇 编辑:程序博客网 时间:2024/05/23 16:54

java输入输出流


一、什么是IO

java中I/O操作主要指使用java进行输入、输出操作。java所有的I/O机制都是基于数据流进行输入输出,这些数据流表示了字符或者字节数据的流动序列。
java.io是大多数面向数据流的输入/输出类的主要软件包。此外,java也对块传输提供支持,在核心库java.nio中采用的便是块io。
流IO简单易用,效率较低;块IO效率很高,但编程比较复杂。

java IO模型:
java的IO模型设计非常优秀,使用Decorator模式,按功能划分stream,您可以动态装配这些Stream。例如,一个具有缓冲的文件输入流,应组合使用FileInputStream和BufferInputStream。

数据流的基本概念

“流是磁盘或其它外围设备中存储的数据的源点或终点。”
在Java类库中,IO部分的内容是很庞大的,因为它涉及的领域很广泛:
标准输入输出,文件的操作,网络上的数据流,字符串流,对象流,zip文件流等等,java中将输入输出抽象称为流
基本概念:
1. 数据流:
一组有序,有起点和终点的字节的数据序列。包括输入流和输出流。
程序从输入流读取数据源。向输出流写入数据。
采用数据流的目的是使得输入输出独立于设备。
InputStream不关心数据源来自何种设备(键盘、文件
、网络);OutputStream不关心数据的目的是何种设备。
2. 数据流分类:
流序列中的数据既可以是未经加工的原始二进制数据,也可以是经一定编码处理后符合某种格式规定的特定数据。因此Java中的流分为两种:
1) 字节流:数据流中最小的数据单元是字节
2) 字符流:数据流中最小的数据单元是字符, Java中的字符是Unicode编码,一个字符占用两个字节。

标准IO

Java程序可通过命令行参数与外界进行简短的信息交换,同时,也规定了与标准输入、输出设备,如键盘、显示器进行信息交换的方式。而通过文件可以与外界进行任意数据形式的信息交换。
1. 命令行参数

public class TestArgs {    public static void main(String[] args) {        for(int i = 0; i < args.length; i++) {            System.out.println("args[" + i + "] is <" + args[i] + ">");        }    }}    

运行命令:java Java C VB
运行结果:

args[0] is <java>args[1] is <C>args[2] is <VB>

2. 标准输入、输出数据流
java系统自带的标准数据流:java.lang.System:

java.lang.System   public final class System  extends Object{static  PrintStream  err;//标准错误流(输出)static  InputStream  in;//标准输入(键盘输入流)  static  PrintStream  out;//标准输出流(显示器输出流)  }  

注意:
(1)System类不能创建对象,只能直接使用它的三个静态成员。
(2)每当main方法被执行时,就自动生成上述三个对象。
1) 标准输出流 System.out
System.out向标准输出设备输出数据,其数据类型为PrintStream。方法:

  Void print(参数)  Void println(参数)

2)标准输入流 System.in
System.in读取标准输入设备数据(从标准输入获取数据,一般是键盘),其数据类型为InputStream。方法:

    int read() //返回ASCII码。若,返回值=-1,说明没有读取到任何字节读取工作结束。     int read(byte[] b) //读入多个字节到缓冲区b中返回值是读入的字节数     import java.io.*;  public class StandardInputOutput {      public static void main(String args[]) {     int b;      try {          System.out.println("please Input:");          while ((b = System.in.read()) != -1) {              System.out.print((char) b);          }      } catch (IOException e) {          System.out.println(e.toString());      }  }  }  

等待键盘输入,键盘输入什么,就打印出什么:

3. 标准错误流
System.err输出标准错误,其数据类型为PrintStream。可查阅API获得详细说明。
println或print方法都通 过重载实现了输出基本数据类型的多个方法,包括输出参数类型为boolean、char、int、long、float和double。同时,也重载实现 了输出参数类型为char[]、String和Object的方法。其中,print(Object)和println(Object)方法在运行时将调 用参数Object的toString方法。

二、java IO层次体系结构

在整个Java.io包中最重要的就是5个类和一个接口。5个类指的是File、OutputStream、InputStream、Writer、Reader;一个接口指的是Serializable
Java I/O主要包括如下几个层次,包含三个部分:
1.流式部分――IO的主体部分;
2.非流式部分――主要包含一些辅助流式部分的类,如:File类、RandomAccessFile类和FileDescriptor等类;
3.其他类–文件读取部分的与安全相关的类,如:SerializablePermission类,以及与本地操作系统相关的文件系统的类,如:FileSystem类和Win32FileSystem类和WinNTFileSystem类。
主要的类:
InputStream(二进制格式操作):抽象类,基于字节的输入操作,是所有输入流的父类。定义了所有输入流都具有的共同特征。
OutputStream(二进制格式操作):抽象类。基于字节的输出操作。是所有输出流的父类。定义了所有输出流都具有的共同特征。
Java中字符是采用Unicode标准,一个字符是16位,即一个字符使用两个字节来表示。为此,JAVA中引入了处理字符的流。
Reader(文件格式操作):抽象类,基于字符的输入操作。
Writer(文件格式操作):抽象类,基于字符的输出操作。
RandomAccessFile(随机文件操作):它的功能丰富,可以从文件的任意位置进行存取(输入输出)操作。

非流式文件类-File类

在Java语言的java.io包中,由File类提供了描述文件和目录的操作与管理方法。但File类不是InputStream、OutputStream或Reader、Writer的子类,因为它不负责数据的输入输出,而专门用来管理磁盘文件与目录。
作用:File类主要用于命名文件、查询文件属性和处理文件目录
例:File f4=new File(“\dir3”);
File f5=new File(f4,”FileTest5.txt”); //在如果 \dir3目录不存在使用f4.mkdir()先创建
一个对应于某磁盘文件或目录的File对象一经创建, 就可以通过调用它的方法来获得文件或目录的属性。
1)public boolean exists( ) 判断文件或目录是否存在
2)public boolean isFile( ) 判断是文件还是目录
3)public boolean isDirectory( ) 判断是文件还是目录
4)public String getName( ) 返回文件名或目录名
5)public String getPath( ) 返回文件或目录的路径。
6)public long length( ) 获取文件的长度
7)public String[ ] list ( ) 将目录中所有文件名保存在字符串数组中返回。
File类中还定义了一些对文件或目录进行管理、操作的方法,常用的方法有:
1) public boolean renameTo( File newFile ); 重命名文件
2) public void delete( ); 删除文件
3) public boolean mkdir( ); 创建目录
4) createNewFile()创建文件对象指定的文件

java IO流类库

java.io包中包含了流式I/O所需要的所有类。在java.io包中有四个基本类:InputStream、OutputStream及Reader、Writer类,它们分别处理字节流和字符流

JDK1.4版本开始引入了新I/O类库,它位于java.nio包中,新I/O类库利用通道和缓冲区等来提高I/O操作的效率.
1. io流的具体分类
一、按I/O类型来总体分类:
1. Memory
1)从/向内存数组读写数据: CharArrayReader、CharArrayWriter、ByteArrayInputStream、ByteArrayOutputStream
2)从/向内存字符串读写数据 StringReader、StringWriter、StringBufferInputStream
2.Pipe管道 实现管道的输入和输出(进程间通信): PipedReader、PipedWriter、PipedInputStream、PipedOutputStream
3.File 文件流 对文件进行读、写操作 :FileReader、FileWriter、FileInputStream、FileOutputStream
4. ObjectSerialization 对象输入、输出 :ObjectInputStream、ObjectOutputStream
5.DataConversion数据流 按基本数据类型读、写(处理的数据是Java的基本类型(如布尔型,字节,整数和浮点数)):DataInputStream、DataOutputStream
6.Printing 包含方便的打印方法 :PrintWriter、PrintStream
7.Buffering缓冲 在读入或写出时,对数据进行缓存,以减少I/O的次数:BufferedReader、BufferedWriter、BufferedInputStream、BufferedOutputStream
8.Filtering滤流,在数据进行读或写时进行过滤:FilterReader、FilterWriter、FilterInputStream、FilterOutputStream过
9.Concatenation合并输入 把多个输入流连接成一个输入流 :SequenceInputStream
10.Counting计数 在读入数据时对行记数 :LineNumberReader、LineNumberInputStream
11.Peeking Ahead 通过缓存机制,进行预读 :PushbackReader、PushbackInputStream
12.Converting between Bytes and Characters 按照一定的编码/解码标准将字节流转换为字符流,或进行反向转换(Stream到Reader,Writer的转换类):InputStreamReader、OutputStreamWriter

二、按数据来源(去向)分类:
1、File(文件): FileInputStream, FileOutputStream, FileReader, FileWriter
2、byte[]:ByteArrayInputStream, ByteArrayOutputStream
3、Char[]: CharArrayReader, CharArrayWriter
4、String: StringBufferInputStream, StringReader, StringWriter
5、网络数据流:InputStream, OutputStream, Reader, Writer

字节流InputStream和OutputStream

1. InputStream抽象类
InputStream为字节输入流,它本身是一个抽象类,必须依靠子类实现各种功能,此抽象类是表示字节输入流的所有类的超类。继承自InputStream的流都是向程序中输入数据的,且数据单位字节(8bit)。
InputStream是输入字节数据用的类,所以InputStream类提供了3种重载的read()方法。InputStream类中常用方法:
(1)public abstract int read():读取一个byte的数据,返回值是高位补0的int类型值。若返回值为-1说明没有读取到任何字节,读取工作结束。
(2)public int read(byte b[]):读取b.length个字节的数据放到b数组中。返回值是读取的字节数。该方法实际上是调用下一个方法实现的。
(3)public int read(byte b[], int off, int len):从输入流中最多读取len个字节的数据,存放到偏移量为off发b数组中
(4)public int available():返回输入流中可以读取的字节数。注意:若输入阻塞,当前线程将被挂起,如果InputStream对象调用这个方法的话,它只会返回0,这个方法必须由继承InputStream类的子类对象调用才有用。
(5)public long skip(long n):忽略输入流的n个字节,返回值是实际忽略的字节数。
(6)public int close(): 在使用完,必须对打开的流进行关闭。
 主要的子类:
1) FileInputStream把一个文件作为InputStream,实现对文件的读取操作
 2) ByteArrayInputStream:把内存中的一个缓冲区作为InputStream使用
 3) StringBufferInputStream:把一个String对象作为InputStream
 4) PipedInputStream:实现了pipe的概念,主要在线程中使用
5) SequenceInputStream:把多个InputStream合并为一个InputStream
2. OutputStream抽象类
OutputStream提供了3个write方法来做数据的输出,这个是和InputStream是相对应的。
(1) public void write(byte b[ ]):将参数b中的字节写到输出流。
(2) public void write(byte b[ ], int off, int len) :将参数b的从偏移量off开始的len个字节写到输出流。
(3)public abstract void write(int b) :先将int转换为byte类型,把低字节写入到输出流中。
(4)public void flush( ) : 将数据缓冲区中数据全部输出,并清空缓冲区。
(5)public void close( ) : 关闭输出流并释放与流相关的系统资源。
主要的子类:
1) ByteArrayOutputStream:把信息存入内存中的一个缓冲区中
2) FileOutputStream:把信息存入文件中
3) PipedOutputStream:实现了pipe的概念,主要在线程中使用
4) SequenceOutputStream:把多个OutStream合并为一个OutStream 流结束的判断:方法read()的返回值为-1时;readLine()的返回值为null时.
3. 文件输入流:FileInputStream类
FileInputStream可以使用read()方法一次读入一个字节,并以int类型返回,或者是使用read()方法时读入至一个byte数组,byte数组的元素有多少个,就读入多少个字节。在将整个文件读取完成或写入完毕的过程中,这么一个byte数组通常被当作缓冲区,因为这么一个byte数组通常扮演承接数据的中间角色。
作用:以文件作为数据输入源的数据流。或者说是打开文件,从文件读数据到内存的类。
使用方法(1)
**File fin=new File(“d:/abc.txt”);
FileInputStream in=new FileInputStream( fin);**
使用方法(2)
FileInputStream in=new FileInputStream(“d: /abc.txt”);

public class TestFile {      public static void main(String args[]) throws IOException {          try{                     FileInputStream rf=new   FileInputStream("InputFromFile.java");              int n=512;   byte  buffer[]=new  byte[n];                 while((rf.read(buffer,0,n)!=-1)&&(n>0)){                 System.out.println(new String(buffer) );              }              System.out.println();              rf.close();      } catch(IOException  IOe){                  System.out.println(IOe.toString());      }      }  }

4. 文件输出流:FileOutputStream类
作用:用来处理以文件作为数据输出目的的数据流;或者说是从内存区读数据入文件
创建一个文件流对象有两种方法:
方式1:File f= new File(“d:/myjava/write.txt “);
FileOutputStream out= new FileOutputStream (f);
方式2:FileOutputStream out=new FileOutputStream(“d:/myjava/write.txt “);
方式3:构造函数将 FileDescriptor()对象作为其参数。
FileDescriptor() fd=new FileDescriptor();
FileOutputStream f2=new FileOutputStream(fd);
方式4:构造函数将文件名作为其第一参数,将布尔值作为第二参数。
FileOutputStream f=new FileOutputStream(“d:/abc.txt”,true);
注意: (1)文件中写数据时,若文件已经存在,则覆盖存在的文件;(2)的读/写操作结束时,应调用close方法关闭流。

    public class TestFile {      public static void main(String args[]) throws IOException {          try {              System.out.println("please Input from      Keyboard");              int count, n = 512;              byte buffer[] = new byte[n];              count = System.in.read(buffer);              FileOutputStream wf = new FileOutputStream("d:/myjava/write.txt");              wf.write(buffer, 0, count);              wf.close(); // 当流写操作结束时,调用close方法关闭流。              System.out.println("Save to the write.txt");          } catch (IOException IOe) {              System.out.println("File Write Error!");          }      }  } 

5. FileInputStream流和FileOutputStream的应用
利用程序将文件file1.txt拷贝到file2.txt中

try {    File inFile = new File("copy.java");          File outFile = new         File("copy2.java");          FileInputStream finS = new FileInputStream(inFile);          FileOutputStream foutS = new FileOutputStream(outFile);          int c;          while ((c = finS.read()) != -1) {              foutS.write(c);          }          finS.close();          foutS.close();      } catch (IOException e) {          System.err.println("FileStreamsTest: " + e);      }  

6. 缓冲输入输出流 BufferedInputStream/ BufferedOutputStream

计算机访问外部设备非常耗时。访问外存的频率越高,造成CPU闲置的概率就越大。为了减少访问外存的次数,应该在一次对外设的访问中,读写更多的数据。缓冲流就是每一个数据流分配一个缓冲区,一个缓冲区就是一个临时存储数据的内存。这样可以减少访问硬盘的次数,提高传输效率。
BufferedInputStream当向缓冲流读取数据时,数据先写到缓冲区,待缓冲区写满后,系统一次性将数据发送给输出设备。
BufferedOutputStream当从缓冲区读取数据时,系统先从缓冲区读出数据,待缓冲区为空时,系统再从输入设备读取到缓冲区。
* 1)将文件读入内存:*
将BufferedInputStream与FileInputStream相接
FileInputStream in=new FileInputStream( “file1.txt ” );
BufferedInputStream bin=new BufferedInputStream( in);
2)将内存写入文件:
将BufferedOutputStream与 FileOutputStream相接
FileOutputStream out=new FileOutputStream(“file1.txt”);
BufferedOutputStream bin=new BufferedInputStream(out);
3)键盘输入流读到内存
将BufferedReader与标准的数据流相接
InputStreamReader sin=new InputStreamReader (System.in) ;
BufferedReader bin=new BufferedReader(sin);

public class ReadWriteToFile {      public static void main(String args[]) throws IOException {          InputStreamReader sin = new InputStreamReader(System.in);          BufferedReader bin = new BufferedReader(sin);          FileWriter out = new FileWriter("myfile.txt");          BufferedWriter bout = new BufferedWriter(out);          String s;          while ((s = bin.readLine()).length() > 0) {              bout.write(s, 0, s.length());          }      }   }  

程序说明:
从键盘读入字符,并写入到文件中BufferedReader类的方法:String readLine()
作用:读一行字符串,以回车符为结束。
BufferedWriter类的方法:bout.write(String s,offset,len)
作用:从缓冲区将字符串s从offset开始,len长度的字符串写到某处。

字符流WriterReader

java中字符是采用Unicode标准,一个字符是16位,使用两个字节表示。为此,java中引入了处理字符的流。
1. Reader抽象类
用于读取字符流的抽象类。子类必须实现的方法只有 read(char[], int, int) 和 close()。但是,多数子类将重写此处定义的一些方法,以提供更高的效率和/或其他功能。

1) FileReader :与FileInputStream对应
主要用来读取字符文件,使用缺省的字符编码,有三种构造函数:
(1)将文件名作为字符串 :FileReader f=new FileReader(“c:/temp.txt”);
(2)构造函数将File对象作为其参数。
   File f=new file(“c:/temp.txt”);
   FileReader f1=new FileReader(f);
(3) 构造函数将FileDescriptor对象作为参数
   FileDescriptor() fd=new FileDescriptor()
   FileReader f2=new FileReader(fd);
[1]用指定字符数组作为参数:CharArrayReader(char[])
[2] 将字符数组作为输入流:CharArrayReader(char[], int, int)
读取字符串,构造函数如下: public StringReader(String s);
2) CharArrayReader:与ByteArrayInputStream对应
3) StringReader: 与StringBufferInputStream对应
4) InputStreamReader
   从输入流读取字节,在将它们转换成字符:Public inputstreamReader(inputstream is);
5) FilterReader: 允许过滤字符流
   protected filterReader(Reader r);
6) BufferReader :接受Reader对象作为参数,并对其添加字符缓冲器,使用readline()方法可以读取一行。
   Public BufferReader(Reader r);
主要方法:
(1) public int read() throws IOException; //读取一个字符,返回值为读取的字符
  (2) public int read(char cbuf[]) throws IOException; /读取一系列字符到数组cbuf[]中,返回值为实际读取的字符的数量/
  (3) public abstract int read(char cbuf[],int off,int len) throws IOException;
  /读取len个字符,从数组cbuf[]的下标off处开始存放,返回值为实际读取的字符数量,该方法必须由子类实现/  
2. Writer抽象类
写入字符流的抽象类。子类必须实现的方法仅有 write(char[], int, int)、flush() 和 close()。但是,多数子类将重写此处定义的一些方法,以提供更高的效率和/或其他功能。 其子类如下:

1) FileWrite: 与FileOutputStream对应
  将字符类型数据写入文件,使用缺省字符编码和缓冲器大小。
  Public FileWrite(file f);
2) chararrayWrite:与ByteArrayOutputStream对应 ,将字符缓冲器用作输出。
   Public CharArrayWrite();
3) PrintWrite:生成格式化输出
   public PrintWriter(outputstream os);
4) filterWriter:用于写入过滤字符流
   protected FilterWriter(Writer w);
5) PipedWriter:与PipedOutputStream对应

6) StringWriter:无与之对应的以字节为导向的stream
主要方法:
  (1) public void write(int c) throws IOException; //将整型值c的低16位写入输出流
  (2) public void write(char cbuf[]) throws IOException; //将字符数组cbuf[]写入输出流
  (3) public abstract void write(char cbuf[],int off,int len) throws IOException; //将字符数组cbuf[]中的从索引为off的位置处开始的len个字符写入输出流
  (4) public void write(String str) throws IOException; //将字符串str中的字符写入输出流
  (5) public void write(String str,int off,int len) throws IOException; //将字符串str 中从索引off开始处的len个字符写入输出流
  (6) flush( ) //刷空输出流,并输出所有被缓存的字节。
  (7)close() 关闭流 public abstract void close() throws IOException
3 .InputStream与Reader差别 OutputStream与Writer差别
InputStream和OutputStream类处理的是字节流,数据流中的最小单位是字节(8个bit)
Reader与Writer处理的是字符流,在处理字符流时涉及了字符编码的转换问题

public class EncodeTest {  private static void readBuff(byte [] buff) throws IOException {     ByteArrayInputStream in =new ByteArrayInputStream(buff);      int data;      while((data=in.read())!=-1)   System.out.print(data+"  ");      System.out.println();     in.close();     }  public static void main(String args[]) throws IOException {     System.out.println("内存中采用unicode字符编码:" );     char   c='好';     int lowBit=c&0xFF;     int highBit=(c&0xFF00)>>8;     System.out.println(""+lowBit+"   "+highBit);     String s="好";     System.out.println("本地操作系统默认字符编码:");     readBuff(s.getBytes());     System.out.println("采用GBK字符编码:");     readBuff(s.getBytes("GBK"));     System.out.println("采用UTF-8字符编码:");           readBuff(s.getBytes("UTF-8"));      }  } 

运行结果:
内存中采用unicode字符编码:
125 89
本地操作系统默认字符编码:
186 195
采用GBK字符编码:
186 195
采用UTF-8字符编码:
229 165 189

Reader类能够将输入流中采用其他编码类型的字符转换为Unicode字符,然后在内存中为其分配内存
Writer类能够将内存中的Unicode字符转换为其他编码类型的字符,再写到输出流中。

IOException异常类的子类

1.public class EOFException :
非正常到达文件尾或输入流尾时,抛出这种类型的异常。
2.public class FileNotFoundException:
当文件找不到时,抛出的异常。
3.public class InterruptedIOException:
当I/O操作被中断时,抛出这种类型的异常。

0 0