字节流(输出流)

博客介绍了两种方法,一是原始的方法,二是采用自动关闭的方法,为相关操作提供了不同思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

1.原始的方法 

public class OutputStreamTest {
    public static void main(String[] args) {
        File file =new File ( "D:"+File.separator+"输入输出流"
                +File.separator+"输入流"+File.separator+"输出流"+File.separator+"Hello.txt");
        //判断目录是否存在,若不存在,自己创建
        File parent=file.getParentFile ();
        if(!parent.exists ()){
            parent.mkdirs();
        }
        FileOutputStream outputStream=null;
        try {
            outputStream=new FileOutputStream ( file );
            outputStream.write ( 65 );
            outputStream.write ( 97 );
            outputStream.write ( 99 );
            String str="I 哎@¥& _!!\n";
            byte[] strByte=str.getBytes ();
            outputStream.write ( strByte );
            outputStream.flush ();
        } catch (java.io.IOException e) {
            e.printStackTrace ( );
        }finally {
            if (outputStream != null) {
                try {
                    outputStream.close ( );
                } catch (IOException e) {
                    e.printStackTrace ( );
                }
            }
        }
    }
}

 2.采用自动关闭的方法

public class OutputStreamTest {
        public static void main(String[] args) {
            File file = new File ( "D:" + File.separator + "输入输出流"
                    + File.separator + "输入流" + File.separator + "输出流" + File.separator + "Hello.txt" );
            File parent = file.getParentFile ( );
            if (!parent.exists ( )) {
                parent.mkdir ( );
            }
            try (FileOutputStream outputStream = new FileOutputStream ( file, true )) {
               outputStream.write ( 75 );
               outputStream.write ( 90 );
               outputStream.write ( 100 );
               String str="我不黑浮游!!";
               byte[] strByte=str.getBytes ();
               outputStream.write ( strByte );
            } catch (FileNotFoundException e) {
                e.printStackTrace ( );
            } catch (IOException e) {
                e.printStackTrace ( );
            }
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值