Java中其它流的使用

1. 标准的输入输出流:

System.in和System.out分别代表了系统标准的输入和输出设备

  • 默认输入设备是:键盘,输出设备是:显示器
  • System.in的类型是InputStream
  • System.out的类型是PrintStream,其是OutputStream的子类 FilterOutputStream 的子类
    修改默认的输入和输出行为:
    在这里插入图片描述

2. 打印流:PrintStream 和PrintWriter

PrintStream ps = null;
try {
    FileOutputStream fos = new FileOutputStream("print.txt");
    // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
    ps = new PrintStream(fos, true);
    if (ps != null) {// 把标准输出流(控制台输出)改成文件
        System.setOut(ps);
    }

    for (int i = 0; i <= 255; i++) {// 输出ASCII字符
        System.out.print((char) i);
        if (i % 50 == 0)
            System.out.println();
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (ps != null) {
        ps.close();
    }
}

说明:
在这里插入图片描述

3. 数据流:DataInputStream 和 DataOutputStream

在这里插入图片描述
**作用:**用于读取或写出基本数据类型的变量或字符串

示例代码:

@Test
public void testDataOutputStream() {
    DataOutputStream dos = null;
    try {
        // 创建连接到指定文件的数据输出流对象
        dos = new DataOutputStream(new FileOutputStream("destData.txt"));
        dos.writeUTF("我爱北京天安门"); // 写UTF字符串
        dos.flush();
        dos.writeBoolean(false); // 写入布尔值
        dos.flush();
        dos.writeLong(1234567890L); // 写入长整数
        dos.flush();
        System.out.println("写文件成功!");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭流对象
        try {
            if (dos != null) { // 关闭过滤流时,会自动关闭它包装的底层节点流
                dos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/*
将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。

注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!

 */
@Test
public void testDataInputStream(){
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(new FileInputStream("destData.txt"));

        String s = dis.readUTF();
        boolean b = dis.readBoolean();
        long l = dis.readLong();

        System.out.println(s);
        System.out.println(b);
        System.out.println(l);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(dis != null){
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值