JAVA-IO流的理解

关系图

 


 OutputStream例子

package com.alex.examples.exceptions;

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
        String data = "中华人民共和国万岁";
        OutputStream outputStream = new FileOutputStream("D:\\测试.txt");
        //将字符串转换成字节
        byte[] bytes = data.getBytes();
        //将数据写入输出流
        outputStream.write(bytes);
        //关闭输出流(一定要记得,用完即关)
        outputStream.close();
    }
}


 InputStream例子

package com.alex.examples.exceptions;

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
        String path = "D:\\测试.txt";

        // 第1步、使用File类找到一个文件
        File f = new File(path);    // 声明File对象

        // 第2步、通过子类实例化父类对象
        InputStream input;    // 准备好一个输入的对象
        input = new FileInputStream(f);    // 通过对象多态性,进行实例化

        // 第3步、进行读操作
        byte b[] = new byte[1024];        // 所有的内容都读到此数组之中
        input.read(b);        // 读取内容   网络编程中 read 方法会阻塞

        // 第4步、关闭输出流
        input.close();                        // 关闭输出流
        System.out.println("内容为:" + new String(b));    // 把byte数组变为字符串输出
    }
}


 InputStreamReader例子

package com.alex.examples.exceptions;

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
        String path = "D:\\测试.txt";
        transReadNoBuf(path);
        transReadByBuf(path);
    }

    public static void transReadNoBuf(String path) throws IOException {
        /**
         * 没有缓冲区,只能使用read()方法。
         */
        InputStreamReader isr = new InputStreamReader(new FileInputStream(path));

        char[] cha = new char[1024];
        int len = isr.read(cha);
        System.out.println(new String(cha, 0, len));
        isr.close();

    }

    public static void transReadByBuf(String path) throws IOException {
        /**
         * 使用缓冲区 可以使用缓冲区对象的 read() 和  readLine()方法。
         */
        BufferedReader bufr = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
        String line;
        while ((line = bufr.readLine()) != null) {
            System.out.println(line);
        }
        bufr.close();
    }
}


 OutputStreamWriter例子

package com.alex.examples.exceptions;

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
        String path = "D:\\测试.txt";
        File f = new File(path);
        Writer out = new OutputStreamWriter(new FileOutputStream(f)); // 字节流变为字符流
        out.write("hello world!!");    // 使用字符流输出
        out.close();
    }
}

 


参考:Java OutputStreamWriter类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值