三、java IO--使用字节流写入文件

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

/**
    二、写出文件
    1、建立联系   File对象  目的地
    2、选择流     文件输出流  OutputStream FileOutputStream
    3、操作  :  write() +flush
    4、释放资源 :关闭
 */
public class WriteFile {
    public static void main(String[] args) {
        String str = "F:/write.txt";
        mywrite(str);
    }
    public static void mywrite(String str){
        File file = new File(str);    //1、建立连接
        OutputStream os = null;
        try {
            //2、选择输出流,以追加形式(在原有内容上追加) 写出文件 必须为true 否则为覆盖
            os = new FileOutputStream(file,true);    
//            //和上一句功能一样,BufferedInputStream是增强流,加上之后能提高输出效率,建议
//            os = new BufferedOutputStream(new FileOutputStream(file,true));
            String string = "Programmer say : Hello World!";
            byte[] data = string.getBytes();    //将字符串转换为字节数组,方便下面写入

            os.write(data, 0, data.length);    //3、写入文件
            os.flush();    //将存储在管道中的数据强制刷新出去
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件没有找到!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("写入文件失败!");
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("关闭输出流失败!");
                }
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/jiaoqiang/p/8378412.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值