流分按照数据流的分类为:输入流和输出流;输入流就是从数据源读取数据到程序中,关键字为继承io包中的InputStream或者Reader;输出流就是将数据从程序写入数据的目的地,关键字是继承io包中的OutputStream或者Writer。

  流按照处理数据的最小单位的不同分类分为字节流和字符流;字节流是以以byte为最小单位进行数据传送,关键字为继承io包的抽象类InputStream或者OutputStream;字符流是以char为最小的单位进行数据传送,关键是继承io包中的Reader或者Writer。

  下面来简单的看看这些流:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 字节输入输出流测试
 * 
 * @author 小明
 *
 */
public class IOTest {

    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer(); // 字符串缓冲
        
        /* 输入流 */
        InputStream in = null;

        try {
            // 1. 打开输入流
            in = new FileInputStream("E:\\jg\\exercise.txt");
            // 2. 读取
//            byte[] b = new byte[128];
            byte[] b = new byte[1024 * 4];
            int len = in.read(b); // 返回读取到的字节数,返回-1表示读取到流结尾
            while(len != -1){
                buffer.append(new String(b, 0, len)); // 将读取到的字节解析为String追加到缓冲
                len = in.read(b);
            }
//            System.out.println("读到" + len + "字节的数据");
            System.out.println(buffer.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 3. 释放资源,关闭输入流
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        /* 输出流 */
        OutputStream out = null;
        
        try {
            File file = new File("D:\\test\\demo\\test.txt");
            if (!file.getParentFile().exists()){ // 文件路径不存在,则创建路径中所有不存在的目录
                file.getParentFile().mkdirs();
            }
            // 1. 打开输出流
            out = new FileOutputStream(file);
            // 2. 写
            out.write(buffer.toString().getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 3. 释放输出流资源
            if (out != null){
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

里面还用到了关键字File,这个关键字是指定路径名的。