字节输出流

                

 

OutputStream此抽象类,是表示输出字节流的所有类的超类。操作的数据都是字节,定义了输出字节流的基本共性功能方法。

一、FileOutputStream类

OutputStream有很多子类,其中子类FileOutputStream可用来写入数据到文件。

FileOutputStream类,即文件输出流,是用于将数据写入 File的输出流。

 构造方法

 二、FileOutputStream类写入数据到文件中

public class FileOutputStreamaa {

    public static void main(String[] args) throws IOException {

      

        //创建存储数据的文件。

        File file = new File("c:\\file.txt");

        //创建一个用于操作文件的字节输出流对象。一创建就必须明确数据存储目的地。

        //输出流目的是文件,会自动创建。如果文件存在,则覆盖。

        FileOutputStream fos = new FileOutputStream(file);

        //调用父类中的write方法。

        byte[] data = "abcde".getBytes();

        fos.write(data);

        //关闭流资源。

        fos.close();

    }

}

三、文件的续写和换行符号

FileOutputStream的构造函数中,可以接收一个boolean类型的值,如果值true,就会在文件末位继续添加,即续写。

  构造方法

 给文件中续写数据和换行

public class FileOutputStreamDemo2 {

    public static void main(String[] args) throws Exception {

        File file = new File("c:\\file.txt");

        FileOutputStream fos = new FileOutputStream(file, true);   //true设置给指定文件续写数据

        String str = "\r\n"+"itcast";      //  "\r\n"实现换行

        fos.write(str.getBytes());

        fos.close();

    }

}

 四、IO异常的处理

我们在实际开发中,异常时如何处理

public class FileOutputStreamDemo3 {

    public static void main(String[] args) {

        File file = new File("c:\\file.txt");

        //定义FileOutputStream的引用

        FileOutputStream fos = null;

        try {

            //创建FileOutputStream对象

            fos = new FileOutputStream(file);

            //写出数据

            fos.write("abcde".getBytes());

        } catch (IOException e) {

            System.out.println(e.toString() + "----");  

            throw new RuntimeException("文件写入失败,请重试");

        } finally {

            //一定要判断fos是否为null,只有不为null时,才可以关闭资源

            if (fos != null) {

                try {

                    fos.close();

                } catch (IOException e) {

                    throw new RuntimeException("关闭资源失败");

                }

            }

        }

    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值