java(三十五)IO流(四)字节输出流

OutputStream是输出字节流的父类,它是一个抽象类

FileOutputStream


把内存中的数据以字节的形式写出到磁盘文件中的输出流,用于将数据写出到文件。

它继承自 OutputStream 类。通过创建 FileOutputStream 对象,可以打开一个文件,并向该文件中写入数据。可以使用 write(int) 方法逐个字节地写入数据,也可以使用 write(byte[]) 方法一次写入多个字节。写入完成后,应该调用 close() 方法关闭流。

应用实例:请使用FileOutputStream 在a.txt 文件中写入”hello,world“,如果文件不存在,会自动创建文件

第一种方法:使用 write(int b) 注意关闭文件流,或刷新文件流

OutputStream os = new FileOutputStream("src/a.txt");
os.write('a');
os.write('b');
os.flush();
os.close();

第二种方法:使用 write(byte[] b)

OutputStream os = new FileOutputStream("src/a.txt");
byte[] b = {'c','b','c'};
os.write(b);
os.close();

os.write("我是中国人".getBytes());

不要把之前数据清空,追加

FileOutputStream,append true

写前几个

byte[] b = {'c','b','d'};
os.write(b,0,2);

换行

os.write('a');
os.write("\r\n".getBytes());
os.write('b');

第三种方法:使用 write(byte[] b,int off,int len)
public class FileOutputStream01 {

    public static void main(String[] args) {



    }



    @Test

    public void writeFile(){

        String filePath = "D:\\a.txt";

        FileOutputStream fileOutputStream = null;



        try {

            fileOutputStream = new FileOutputStream(filePath);

            //写入一个字符串

            String str = "hello,Jay!";

            fileOutputStream.write(str.getBytes(),0,str.length());

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                fileOutputStream.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

}

练习:将枯藤老树昏鸦,小桥流水人家,古道西风瘦马,夕阳西下,断肠人在天涯 出入到文件里

OutputStream out = new FileOutputStream("d:\\2.txt", true);
try {

    String ss = "枯藤老树昏鸦,小桥流水人家,古道西风瘦马,夕阳西下,断肠人在天涯";
    byte[] bytes = ss.getBytes();//getBytes()方法把字符串转为字节数组
    out.write(bytes);
}catch (Exception ex){
    ex.printStackTrace();
}finally {
    out.flush();
    out.close();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Allen019

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值