io流

    /**
     * 字节输出流 OutputStream
     * @throws IOException 
     */
    @Test
    public void testOutputStream() throws IOException {
//        File file = new File("D:\end111.log");
        File file = new File("D:" + File.separator + "testjava"
                + File.separator + "myinfo.txt"); // 指定一个文件的路径
        if (!file.getParentFile().exists()) { // 先创建文件夹
            file.getParentFile().mkdirs(); // 创建文件夹
        }
        OutputStream out = new FileOutputStream(file); // 向上转型
//        OutputStream out = new FileOutputStream(file, true); // 向上转型
        String str = "Hello World ..
"; // 字符串
        byte data[] = str.getBytes(); // 将字符串变为字节数组
        out.write(data); // 全部输出
        out.close();
    }


/**
     * 字节输入流InputStream
     * 使用最多的读取是while这种形式的
     */
    @Test
    public void testInputStream2() throws IOException {
        File file = new File("D:" + File.separator + "testjava"
                + File.separator + "myinfo.txt"); // 指定一个文件的路径
        if (file.exists()) { // 文件要存在才能够进行读取
            InputStream input = new FileInputStream(file); // 找到要输入的文件
            StringBuffer buf = new StringBuffer();
            int temp = 0;
            // 将input.read()读取的内容给temp,如果temp的内容不是-1,则表示不是文件底部
            while ((temp = input.read()) != -1) {
                buf.append((char) temp);// 内容的保存
            }
            input.close();
            System.out.println("输入内容是:【" + buf + "】");
        }
    }
    
    /**
     * 字符输出流:Writer
     */
    @Test
    public void testWriter() throws IOException {
        File file = new File("D:" + File.separator + "testjava"
                + File.separator + "myinfo.txt"); // 指定一个文件的路径
        if (!file.getParentFile().exists()) { // 先创建文件夹
            file.getParentFile().mkdirs(); // 创建文件夹
        }
        Writer out = new FileWriter(file); // 向上转型
        String str = "Hello World ."; // 字符串
        out.write(str); // 全部输出
        out.close(); // 输出关闭
    }
    
    /**
     * 字符输入流:Reader
     */
    @Test
    public void testReader() throws IOException {
        File file = new File("D:" + File.separator + "testjava"
                + File.separator + "myinfo.txt"); // 指定一个文件的路径
        if (file.exists()) { // 文件要存在才能够进行读取
            Reader input = new FileReader(file); // 找到要输入的文件
            char data[] = new char[1024]; // 准备一个可以加载数据的数组
            int len = input.read(data); // 把数据保存在字节数组之中,返回读取个数
            input.close(); // 关闭
            System.out.println("读取的数据:【" + new String(data, 0, len) + "】");
        }
    }
原文地址:https://www.cnblogs.com/mabiao008/p/6322862.html