文件的复制(逐字节/整体)

本文介绍两种使用Java进行文件复制的方法:一种是逐字节读取并写入;另一种是通过一次性读取整个文件内容再写入的方式。这两种方法均利用了FileInputStream和FileOutputStream类来完成文件的读写操作。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

//逐字节读取,复制

public class io1 {
    public static void main (String []args) throws IOException{
        //读文件
        FileInputStream fis=new FileInputStream("D:\\Desktop\\文件复制练习\\11.mp4");
         //1.要读取的对象(文件内的内容)
         FileOutputStream fos=new FileOutputStream("D:\\Desktop\\文件复制练习\\12.mp4");
         //单独进行写入,要确定写什么,写到什么地方
         //要写入的对象(写入哪个文件)
         
         
         
         //确定读取方式:1.逐字节的读取,2.整个读取,
         int a = fis.read();
         //     读取每一个字节
                         
        while( a!= -1){//读取的数据与-1比较            
            fos.write(a);
        // 循环内先进行输出,后再次进行读取             
         a=fis.read();     //出现死循环因为没有a=
         }  
         fis.close();//输入流
         fos.flush();//
         fos.close();//关闭输出流
         }
    }
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;





public class io2 {
    public static void main (String []args) throws IOException{
        //读文件
        FileInputStream fis=new FileInputStream("D:\\Desktop\\文件复制练习\\11.MP4");
         //1.要读取的对象(文件内的内容)
         FileOutputStream fos=new FileOutputStream("D:\\Desktop\\文件复制练习\\16.MP4");
         //单独进行写入,要确定写什么,写到什么地方
         //要写入的对象(写入哪个文件)
                           
         //确定读取方式:1.逐字节的读取,2.整个读取,
         
         
         //整个读取                                                 
          File f=new File ("D:\\Desktop\\文件复制练习\\11.MP4");    
           int c=(int)f.length();
           
           //获取输入文件的长度               
           byte[]b=new byte [c];
           
           //将文件字节长度。放入同样长度的数组中
           
         fis.read(b,0,b.length);    //读取数据   
        
         fos.write(b, 0, b.length);
         fis.close();//输入流
         fos.flush();//
         fos.close();//关闭输出流
         }
    }

 

转载于:https://www.cnblogs.com/-strong/p/7157283.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值