复制文件

package file;

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

/**
 * Created by Administrator on 2018/1/25.
 * 复制文件
 * read():每次读取一个字节,返回该字节对应的ASCII码
 * read(byte b[]):每次读取b[]长度的字节,返回读取的字节数量
 * write(words,0,length):将words中从0开始共length字节写入文件中
 * flush():强制将缓冲区的数据写到输出流中
 * available():不将数据取出来,返回输入流中总的字节数
 * read()将数据从输入流中取出来,所以第二次read()时,不能读到第一次的数据
 * 为什么要循环读取?
 * 答:假如源文件的字节有7个,此时定义bytes数组的长度是3,那么每次read(bytes)最多只能读取3个,
 * 所以此时就要读取3次(3+3+1)才能读完源文件。故采用循环。
 */
public class InputAndOutputFile {
    public static void main(String[] args) {
        FileInputStream fis=null;
        FileOutputStream fos=null;
        try {
            //1、创建输入流对象,负责读取D:/ 我的青春谁做主.txt文件
            fis = new FileInputStream("D:/我的青春谁做主.txt");
            //2、创建输出流对象,负责写入myPrime文件
            fos = new FileOutputStream("D:/myPrime.txt",false);
            //3、创建中转站数组,存放每次读取的内容
            byte[] words=new byte[3];
            //4、通过循环实现文件读取
            int len = -1;
            int i = 0;
            while((len = fis.read(words))!=-1){
                System.out.println(++i);
                fos.write(words,0,len);
            }

          /*  int length = fis.available();
            fis.read(words);
            System.out.println(new String(words));
            fos.write(words,0,length);*/

            fos.flush();
            System.out.println("复制完成,请查看文件!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //5、关闭流
            try {
                if(fos!=null)
                    fos.close();
                if(fis!=null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值