08_IO

IOInput/Output

1 BIOS基本的输入输出系统

为什么要有输入输出流?

答:程序是运行在内存里面的,JAVA程序需要和它所运行的内存之外的节点互相传递数据就需要使用IO

JAVA与其它节点之间互换数据使用的通道。

4流的分类

(1)按方向分:输入流、输出流。

(2)按传输内容分:字节流、字符流。

(3)按功能分:节点流、处理流。

         节点流:流的两端直接接在节点上,功能负责两节点传输数据。

 处理流:不能直接接节点,只能套在节点上使用,作用给节点流增加额外的功能

JAVA的流都是从四个抽象类继承而来

InputStream(字节流)

OutputStream(字节流)

Reader(字符流)

Writer(字符流)

 

5节点流:

FileInputStream/FileOutputStream

FileReader/FileWriter

 

注意:只要是JAVA和别的内容建立连接(IODB连接、socket连接)一、要消耗时间;二、消耗资源;所以连接后必须关闭。

 

字节流中使用的是ISO-8859-1编码,只有128个。

字符流中使用的是unicode编码(UTF-8.

 

文件写:write()如果流关闭了,再向文件里写内容,会被覆盖。

 

文件的复制:

import java.io.*;

public class Test throws Exception {

  public static void main(String[] args) {

      OutputStream os = new FileOutputStream("e:/Myiava/Test1.txt");

      InputStream is = new FileInputStream("e:/Myiava/Test2.txt");    

      int n = -1;

      while((n = is.read()) != -1) {

          os.write((char)n);

      }

      os.close();

      is.close();

  }

}

6处理流

缓冲流(给节点增加缓冲区的功能)

缓冲区:硬盘的损耗速度与读写的次数有关。使用缓冲区,可以大大减少读写次数。

import java.io.*;

public class Test throws Exception {

  public static void main(String[] args) {

    OutputStream os = new FileOutputStream("e:/Myiava/Test1.txt");

    BufferedOutputStream bos = new BufferedOutputStream(os);    

    bos.write();

    bos.flush();//强制性地将文件写出去,再将缓冲区清空

    bos.close();

  }

}

 

7转换流

把字节流转换成字符流,把字符流转换成字节流。

InputStreamReader   OutputStreamWriter

8 Data(数据流)

流里面传输的只能是字符和字节,不能传输JAVA的数据类型,数据流可以直接读取与JAVA相关的数据类型(四类八种加上String)。

import java.io.*;

public class Test throws Exception{

  public static void main(String[] args) {

    OutputStream os = new FileOutputStream("e:/Myiava/Test1.txt");

    DataOutputStream dos = new DataOutputStream(os);    

    dos.writeInt(1234);

    dos.close();

 

     DataInputStream dis = new DataInputStream(new   

   FileOutputStream("e:/Myiava/Test1.txt"));

     int num = dis.readInt();

dis.close();

     System.out.println(num);

  }

}

9 Object

Object流是JAVA 5.0的新特性序列化

序列化:把JAVA中的对象写出去(跟数据库中概念:持久化差不多);

反序列化:把写进来的数据封装.

import java.io.*;

public class Test throws Exception{

  public static void main(String[] args) {

    FileOutputStream fos = new FileOutputStream("e:/Myiava/Test1.txt");

    ObjectOutputStream oos = new ObjectOutputStream(oos);    

    oos.writeObject(new Person("jack",300,400));

    oos.close();

  }

}

 

class Person implements Serializable{

String name;

int x;

int y;

public Person(String name,int x,int y) {

  this.name = name;

    this.x = x;

    this.y = y;

  }

}

 

10关键字transient 瞬间的,透明的

可以使Object流读不出被transient修饰过的属性。

 

posted @ 2013-02-14 21:12  bod08liukang  阅读(118)  评论(0)    收藏  举报