14ava语法回顾之inputsteam&&outputsteam

Java语法回顾之InputSteam&&OutputSteam


读了那么多年的书让我明白一个道理。人要稳重,不要想到啥就做啥。做一行越久即使你不会,几年之后慢慢的你也会了,加上一点努力你或许你能成为别人眼中的专家。

通过字节流往文件中写数据


/*
 * 通过字节流往文件中写数据。
 * 
 * 字节输出流操作步骤:
 * A:创建字节输出流对象
 * B:调用写数据的方法
 * C:释放资源
 */

通过字节流往文件中写数据代码测试

public class FileOutputStreamDemo {
    public static void main(String[] args) throws IOException {
        // 创建字节输出流对象(true为追加写入)
        // FileOutputStream fos = new FileOutputStream("a.txt",true);
        FileOutputStream fos = new FileOutputStream("a.txt");

        // 调用写数据的方法
        // 写入一个字节
        // fos.write(97);
        // fos.write(98);
        // fos.write(99);
        // fos.flush();
        // 写一个字节数组
        // byte[] bys = { 97, 98, 99, 100, 101 };
        byte[] bys = "abcde".getBytes();
        // fos.write(bys);
        // 写一个字节数组的一部分
        fos.write(bys, 0, 2);
        // 释放资源
        fos.close();
    }
}

字节输入流操作步骤

/*
 * 字节输入流操作步骤:
 * A:创建字节输入流对象
 * B:调用读取数据的方式,并显示
 * C:释放资源
 */

字节输入流操作步骤代码测试


public class FileInputStreamDemo {
    public static void main(String[] args) throws IOException {
        // 创建字节输入流对象
        FileInputStream fis = new FileInputStream("b.txt");

        // 调用读取数据的方式,并显示
        // 方式1
        // int by = 0;
        // while ((by = fis.read()) != -1) {
        // System.out.println(by);
        // }

        // 方式2
        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = fis.read(bys)) != -1) {
            System.out.print(new String(bys, 0, len));
        }

        // 释放资源
        fis.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值