java io流

来源:互联网 发布:世界卫生组织官网数据 编辑:程序博客网 时间:2024/06/06 14:11

一、数据流

1.流

在Java中把不同的数据源与程序之间的数据传输都抽象表述为“流”(stream),以实现相对统一和简单的输入/输出操作方式。传输中的数据就像流水一样,也称为数据流。

2 .I/O数据流的分类方式

数据流分为输入流和输出流两类。输入流只能读取不能写。而输出流只能写不能读。(这里站在程序的角度来确定出入方向,这块我看了很多java教程之后才理解,即将数据从程序外部传送到程序中谓之“输入”数据,将程序中的数据传送到外部谓之“输出”数据。)

二、字符流

1.字符输入流Reader

Reader类为所有面向字符的输入流的超类,声明为java.io中的抽象类。

public int read():读取一个字符,返回的是读到的那个字符。如果读到流的末尾,返回-1。

public int read(char[] cbuf):将读到的字符存入指定的数组中,返回的是实际读取的字符数。如果读到流的末尾,返回-1。

public abstract int read(char[] cbuf,int off,int len):将读到的字符存入数组的指定位置(off),每次最多读len个字符,返回实际读取的字符数。如果读到流的末尾,返回-1。

close():读取字符其实用的是window系统的功能,使用完毕后,进行资源的释放。

 

2.字符输出流writer

Weiter类为所有面向字符的输出流的超类,声明为java.io中的抽象类。

public void write(int c):将一个字符写入到流中。

public void write(char[]):将数组中的字符依次写出。

public abstract void write(char[] bcbuf,int off,int len):将数组中下标off开始的len个字符写出。

public void write(String):将一个字符串写入到流中。

public abstract void flush():刷新流,将流中的数据刷新到目的地中,流还存在。

public abstreact void close():关闭资源,关闭前会先调用flush,刷新流中的数据去目的地,然后流关闭。


三、FileWriter与FileReader区别与使用实例


FileWriter继承了 java.io.OutputStreamWriter

FileReader继承了 java.io.InputStreamReader


package com.zhoum.intelligentler.core;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class StreamDemo {
    
    public static boolean fileWrite(String filePath){
        
        try {
            FileWriter fw = new FileWriter(filePath);//在filePath路径下创建相应文件
            
            char ch = '中';
            char attr[] = {'a', 'b', 'c'};
            
            fw.write(ch);
            fw.write(attr);
            fw.write("\t花旗无欢");
            fw.write("\t1993-09-11");
            fw.write("\t上海");
            
            fw.flush();//只有输出流需要刷新
            fw.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public static boolean fileRead(String filePath){
        
        FileReader fr = null;
        
        try {
            fr = new FileReader(filePath);
            char attr[] = new char[1024];
            StringBuffer sb = new StringBuffer();
            fr.read(attr);
            for(char c : attr){
                sb.append(c);
            }
            System.out.println(sb);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (fr != null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        
        String filePath = "E:/test/demo.txt";//在java中,文件路径在系统中是'\',但在java中为'/'或'\\'
        if (fileWrite(filePath)){
            System.out.println("============开始读取文件=============");
            fileRead(filePath);
            System.out.println("============结束读取文件=============");
        }
        
    }
}


四、高效的输入/输出 BufferedReader与BufferedWriter


BufferedReader in = new BufferedReader(new FileReader(filePath));//读指定目录下的文件

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//读取控制台输入

从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。如果没有缓冲,则每次调用 read() 或 readLine() 都会导致从文件中读取字节,并将其转换为字符后返回,而这是极其低效的。  


五、FileInputStream与FileOutputStream和FileWriter与FileReader的区别

1、概念

FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。 

FileOutputStream 用于写入诸如图像数据之类的原始字节的流。要写入字符流,请考虑使用 FileWriter。

2、继承关系

java.lang.Object
  继承者 java.io.OutputStream
      继承者 java.io.FileOutputStream

java.lang.Object
  继承者 java.io.InputStream
      继承者 java.io.FileInputStream

FileInputStream与FileOutputStream直接继承了InputStreamOutputStream

java.lang.Object
  继承者 java.io.Reader
      继承者 java.io.InputStreamReader
          继承者 java.io.FileReader

java.lang.Object
  继承者 java.io.Writer
      继承者 java.io.OutputStreamWriter
          继承者 java.io.FileWriter

FileWriter与FileReader还间接继承了Writer与Reader


六、解决编码问题

Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath),"GBK"));

Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "GBK"));


FileInputStream(filePath)将指定文件的字节流向字符流的转换。

InputStreamReader 进行读取。可以设置编码。

BufferedReader 设置缓冲区,可以高效输出。

OutputStreamWriter 与 InputStreamReader字符流通向字节流的桥梁:可使用指定的 charset 将要写入流中的字符编码成字节


七、对象流 ObjectOutputStream与ObjectInputStream

对象流顾名思义就是在传输流中存放的是对象,在存储的对象类中必须实现Serializable接口。

package com.zhoum.intelligentler.orm;

import java.io.Serializable;

public class User implements Serializable{
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String userName;
    private String passWord;
    private double salary;
    
    public User(Integer id, String userName, String passWord, double salary){
        this.id = id;
        this.userName = userName;
        this.passWord = passWord;
        this.salary = salary;
    }
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
}

对象输入和输出流实例

public static void objectWrite(String filePath){
        
        ObjectOutputStream oos = null;
        
        try {
        
            oos = new ObjectOutputStream(new FileOutputStream(filePath));
            
            User user = new User(1, "花旗无欢", "1234656", 8888);
            User user2 = new User(2, "程序员", "aaa", 6666);
            User[] users = new User[2];
            users[0] = user;
            users[1] = user2;
            oos.writeObject(users);
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos!=null){
                try {
                    oos.flush();
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                
            }
        }
    }
    
    public static void objectRead(String filePath){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(filePath));
            User[] users = (User[]) ois.readObject();
            for(User user : users){
                System.out.println("id=" + user.getId() 
                           + " userName=" + user.getUserName()
                           + " password=" + user.getPassWord()
                           + " salary=" + user.getSalary());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
         
    }

运行结果:

id=1 userName=花旗无欢 password=1234656 salary=8888.0
id=2 userName=程序员 password=aaa salary=6666.0

0 0
原创粉丝点击