Java实现文件拷贝(字节流)

/**
 * 拷贝文件示例(字节流)
 */
package JavaIO;

import java.io.*;

/**
 * @author 16026
 *
 */
public class CopyPicture {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        copy();
    }

    public static void copy(){
        //创建字节输入输出流
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream("E:\\薛之谦 - 认真的雪.mp3");    //所要读取的文件地址
            fos = new FileOutputStream("E:\\认真的雪.mp3");     //所要写入的文件地址

            int num = 0;

            byte [] by = new byte[1024];

            while((num = fis.read(by)) != -1){  //读取文件
                fos.write(by, 0, num);          //写入文件
            }


        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{                               //关闭资源
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

你可能感兴趣的:(java学习)