java学习初探十七之IO流_FileOutputStream

1.

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

public class StreamTest06 {
    public static void main(String[] args) {
        FileOutputStream fileOutputStream=null;
        try {
            //1.创建文件字节输出流
            // fileOutputStream=new FileOutputStream("temp09.txt");
             //以追加的方式写入
            fileOutputStream=new FileOutputStream("temp09.txt",true);
            //2.开始写
             String msString="HelloWorld";
             //将String转换成byte数组
             byte[] bytes=msString.getBytes();
             //将byte数组中所以数据写入
             //fileOutputStream.write(bytes);
             //将byte数组中一部分写入
             fileOutputStream.write(bytes, 0, 4);
            //推荐最后的时候为了保证数据完全写入硬盘,所以要刷新
             fileOutputStream.flush();//强制刷新
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(fileOutputStream!=null) {
                try {
                    fileOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }
}

2.copy文件

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * 关于文件的赋值粘贴
 * @author LK
 *
 */
public class StreamTest07 {

    public static void main(String[] args) throws Exception {
    //创建输入流
    FileInputStream fileInputStream=new FileInputStream("temp09.txt");
    //创建输出流
    FileOutputStream fileOutputStream=new FileOutputStream("temp10.txt");
    //一边读,一边写
    byte[] bytes=new byte[1024];
     int temp=0;
     while ((temp=fileInputStream.read(bytes))!=-1) {
        //将byte数组中内容直接写入
         fileOutputStream.write(bytes,0,temp);

    }
    //刷新
    fileOutputStream.flush();
    //关闭
    fileInputStream.close();
    fileOutputStream.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值