java_IO

 流的分类:

按数据流的方向分为输入流和输出流         输入和输出是对于程序来说的

按处理数据单位不同分为字符流和字节流(一个字符为两个字节)

按照功能不同分为节点流和处理流

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

字符流使用uniode编码

流未关闭的时候,向文件写内容是追加的,关闭后再写会覆盖

节点流为从一个特定的数据源读写数据(流的两端直接接在节点上,功能负责两个节点传输数据)

 

 

处理流是连接在已存在的流上,通过对数据的处理为程序提供更强大的读写功能(不能直接接在节点流上,只能套在节点流上。作用是给节点流增加额外的功能,处理流不能单独使用)

InputStream

基本方法:(具体可见API)

  int read() throws IOException
  //从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。
  //如果到达流的末尾,则返回 -1。

  int read(byte[] b) throws IOException
  //从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
  //读入缓冲区的总字节数;如果因为已经到达流末尾而不再有数据可用,则返回 -1。

  int read(byte[] b, int off, int len) throws IOException
  //将输入流中最多 len 个数据字节读入 byte 数组。尝试读取 len 个字节,但读取的字节也可能小于该值。以整数形式返回实际读取的字节数。将读取的第一个字节存储在元素 b[off] 中。
  //读入缓冲区的总字节数;如果因为已到达流末尾而不再有数据可用,则返回 -1。


  void close() throws IOException
  //关闭此输入流并释放与该流关联的所有系统资源。
  //InputStream 的 close 方法不执行任何操作。

OutputStream

  void write(int b) throws IOException
  //将指定的字节写入此输出流。
  void write(byte[] b) throws IOException
  //将 b.length 个字节从指定的 byte 数组写入此输出流
  void write(byte[] b, int off, int len) throws IOException
  //将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
  //如果 b 为 null,则抛出 NullPointerException。如果 off 为负,或 len 为负,或者 off+len 大于数组 b 的长度,则抛出 IndexOutOfBoundsException。
  void flush() throws IOException
  //将输出流中缓冲的数据全部写出到目的地
  void close() throws IOException
  //关闭此输出流并释放与此流有关的所有系统资源。

  //close之前用flush清空缓存

Reader 基本方法:

  同上(不同以字符为单位)

Writer基本方法:

  public void write(String str) throws IOException
  //将字符串写入输出流。
  //因为String有toCharArray方法将String转换为字符数组
  void write(String str, int off, int len) throws IOException
  //写入字符串的某一部分。
  // str - 字符串;off - 相对初始写入字符的偏移量;len - 要写入的字符数

节点流类型:

处理流类型:

关闭处理流是,节点流自动关闭

1、缓冲流:套接在相应字节流之上,对数据的读写提供缓冲的功能。

   缓冲区:硬盘的损耗数度是跟硬盘读写次数有关,缓冲区的使用就是为了减少读写次数,保护硬盘

  BufferedWriter、BufferedReader、BufferedInputStream、BufferedOutputStream

  注意:

  •  缓冲输入流支持其父类的mark和reset方法
  •  BufferedReader提供了readLine方法用于读取一行字符串
  •  BufferedWriter提供newLine方法,写入一个换行
  •  对于输出缓冲流,写出的数据选在内存中缓存,使用flush方法将内存中的数据写出

2、转换流: 将字节流转换成字符流

  InputStreamReader、OutputStreamWriter

  注意:

  •  InputStreamReader与InputStream套接
  •  OutStreamWriter与OutputStream套接
  •  转换流在构造时可以指定其编码集合(gbk 国标;ISO8859-1 西欧语言)   

 3、数据流:可以存取JAVA原始类型数据(int,float等(四类八种+String))

  DataInputStream、 DataOutputStream

4、Print流(打印流)

  PrintWriter和PrintStream都属于输出流,分别对应字节和字符

  PrintWriter和PrintStream提供了重载的Print

  Println可以用于多种数据类型的输出

  PrintWriter和PrintStream输出不会抛出异常

  PrintWriter和PrintStream有自动flush功能

5、Object流:直接将Object写入或读出

  ObjectInputStream , ObjectOutputStream

  序列化:将一个Object直接转换为字节流写到硬盘和网络中

   Serializable可序列化的;此接口内无方法

   transient透明的;在序列化时不予考虑;若输出则为零

  externalisable;自己控制序列化过程

例 1:InputStream

import java.io.*;
public class TestFileInputStream {
  public static void main(String[] args) {
    int b = 0;
    FileInputStream in = null;
    try {
      in = new FileInputStream("d:\\share\\java\\io\\TestFileInputStream.java");
    } catch (FileNotFoundException e) {
      System.out.println("找不到指定文件"); 
      System.exit(-1);
    }
    
    try {
      long num = 0;
      while((b=in.read())!=-1){
        System.out.print((char)b); 
        num++;
      }
      in.close();  
      System.out.println();
      System.out.println("共读取了 "+num+" 个字节");
    } catch (IOException e1) {
      System.out.println("文件读取错误"); System.exit(-1);
    }
  }
}

例2:OutputStream

import java.io.*;
public class TestFileOutputStream {
  public static void main(String[] args) {
      int b = 0;
      FileInputStream in = null;
      FileOutputStream out = null;
      try {
        in = new FileInputStream("d:/share/java/HelloWorld.java");
        out = new FileOutputStream("d:/share/java/io/HW.java");
        while((b=in.read())!=-1){
          out.write(b);
        }
        in.close(); 
        out.close();
      } catch (FileNotFoundException e2) {
        System.out.println("找不到指定文件"); System.exit(-1);
      } catch (IOException e1) {
        System.out.println("文件复制错误"); System.exit(-1);
      }
      System.out.println("文件已复制");
  }
}

例3:Reader

import java.io.*;
public class TestFileReader {
  public static void main(String[] args) {
    FileReader fr = null; 
    int c = 0;
    try {
      fr = new FileReader("d:\\share\\java\\io\\TestFileReader.java");
      int ln = 0;
      while ((c = fr.read()) != -1) {
        //char ch = (char) fr.read();
        System.out.print((char)c);
        //if (++ln >= 100) { System.out.println(); ln = 0;}
      }
      fr.close();
    } catch (FileNotFoundException e) {
      System.out.println("找不到指定文件");
    } catch (IOException e) {
      System.out.println("文件读取错误");
    }

  }
}

例4:Writer

import java.io.*;
public class TestFileWriter {
  public static void main(String[] args) {
    FileWriter fw = null;
    try {
      fw = new FileWriter("d:\\bak\\unicode.dat");
      for(int c=0;c<=50000;c++){
        fw.write(c);
      }
      fw.close();
    } catch (IOException e1) {
        e1.printStackTrace();
      System.out.println("文件写入错误");
      System.exit(-1);
    }
  }
}

 例5:BufferedStream

import java.io.*;

public class TestBufferedStream1 {
    public static void main(String[] args) {
        try {
            int b = 0;
            FileInputStream fis = new FileInputStream("g:/JAVA基础/TestFileInputStream.java" );
            BufferedInputStream bis = new BufferedInputStream(fis);//注意BufferedInputStream的构造函数
            System.out.println(bis.read());
            System.out.println(bis.read());
            bis.mark(100);          //标记第100个字节
            for(int i=0; i<10 && (b=bis.read())!=-1;i++){         // 从第100个字节开始
                System.out.print((char)b+" ");
            }
            System.out.println();
            bis.reset();           //回到第100个字节
            for(int i=0; i<10 && (b=bis.read())!=-1;i++){
                System.out.print((char)b+" ");
            }
            bis.close();
        }catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("未找到文件");
        } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件读取错误");
        }
    }
}

运行结果:

               不是读到到显示屏上,读到b上,在内存中的一块区域,显示屏上是由于打印的结果

例6:BufferedWriter BufferedReader

import java.io.*;

public class TestBufferedStream2 {

    public static void main(String[] args) {
            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter("g:/JAVA基础/TestFileInputStream.java"));
                BufferedReader br = new BufferedReader(new FileReader("g:/JAVA基础/TestFileInputStream.java"));
                String c=null;
                for(int i=0; i<10; i++){
                    c=String.valueOf(Math.random());
                    bw.write(c);
                    bw.newLine();
                }
                bw.flush();
                String b=null;
                while((b=br.readLine())!=null){
                    System.out.println(b);
                }
                bw.close();
                br.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

 例7:OutputStreamWriter

import java.io.*;

public class TranseForm1 {
    public static void main(String[] args) {
            try {
                OutputStreamWriter osw = new OutputStreamWriter(
                        new FileOutputStream("g:/JAVA基础/TestFileInputStream.java"));
                osw.write("sdjfghgklhaksh");
                System.out.println(osw.getEncoding());//返回此流使用的字符编码的名称
                osw.flush();
                osw.close();
                osw = new OutputStreamWriter(
                        new  FileOutputStream("g:/JAVA基础/TestFileInputStream.java",true),"ISO8859-1");//true为续写即接着原来的写
                osw.write("sdjfghgklhaksh");
                System.out.println(osw.getEncoding());
                osw.flush();
                osw.close();
            }catch (FileNotFoundException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

运行结果:

 打开文件 :

              

例8:InputStreamReader

import java.io.*;
public class TestTransForm2 {
  public static void main(String args[]) {
    InputStreamReader isr = 
            new InputStreamReader(System.in);   
    BufferedReader br = new BufferedReader(isr);
    String s = null;
    try {
      s = br.readLine();
      while(s!=null){
        if(s.equalsIgnoreCase("exit")) break;
        System.out.println(s.toUpperCase());
        s = br.readLine();
      }
      br.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
} //阻塞

 例9:DataInputStream,DataOutputStream

import java.io.*;
public class TestDataStream {
    public static void main(String[] args) {
        ByteArrayOutputStream bao =  new ByteArrayOutputStream ();
        DataOutputStream dos = new DataOutputStream(bao);
        try {
            dos.writeDouble(Math.random());
            dos.writeBoolean(true);
            ByteArrayInputStream bai = new ByteArrayInputStream(bao.toByteArray());
            DataInputStream dis = new DataInputStream(bai);
            System.out.println(bai.available());
            System.out.println(dis.readDouble());
            System.out.println(dis.readBoolean());
            dos.close();
            dis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行结果:

    

例10:PrintStream

import java.io.*;
public class TestPrintStream1 {

    public static void main(String[] args) {
        try {
            FileOutputStream fos =  new FileOutputStream("g:/JAVA基础/TestFileInputStream.java");
            PrintStream ps = new PrintStream(fos);
            if(ps!=null){
                System.setOut(ps);//将输出方向指向Ps
            }
            for(int i = 0 ; i < 100 ; i++){
                System.out.print((char)i + " ");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }        
    }
}

 

import java.io.*;
public class TestPrintStream2 {
  public static void main(String[] args) {
    String filename = args[0];              //输入的第一个参数
    if(filename!=null){list(filename,System.out);}
  }
  public static void list(String f,PrintStream fs){
    try {
      BufferedReader br = 
                  new BufferedReader(new FileReader(f));
      String s = null; 
      while((s=br.readLine())!=null){
        fs.println(s);            
      }
      br.close();
    } catch (IOException e) {
      fs.println("无法读取文件");
    }
  }
}

运行结果:读出filename中的内容

此程序必须用cmd编译运行

import java.io.*;
import java.util.Date;

public class TestPrintStream3 {

    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            FileWriter fw = new FileWriter("g:/JAVA基础/TestFileInputStream.java",true);
            PrintWriter log = new PrintWriter(fw,true);
            String s = null;
            while((s=br.readLine())!=null){
                if(s.equalsIgnoreCase("exit")) break;
                System.out.println(s.toUpperCase());
                log.println("----");
                log.println(s.toUpperCase());
                log.flush();
            }
            log.println("===="+new Date()+"====");// 生成日期
            log.flush();
            log.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行结果:

  将输入的字母变为大写;且记录在文件中显示日期;输入exit退出

例11:ObjectInputStream,ObjectOutputStream

import java.io.*;

public class TestObjectIO {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        T t =new T();
        t.l = 4;
        FileOutputStream fos = new FileOutputStream ("g:/JAVA基础/TestFileInputStream.java");
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(t);
        os.flush();
        os.close();
        FileInputStream fis = new FileInputStream("g:/JAVA基础/TestFileInputStream.java");
        ObjectInputStream oi = new ObjectInputStream(fis);
        T tr = (T)oi.readObject();
        System.out.println(tr.f+" "+tr.l+" "+tr.m+" "+tr.n);
    }
}
class T implements Serializable{
    int n = 8;
    int f= 3;
    double m = 2.3;
    /*transient*/ int l = 6;    
}

运行结果:   

加了transient后:

 

posted @ 2017-08-31 20:27  Lune-Qiu  阅读(220)  评论(0编辑  收藏  举报