IO流的应用——Copy文件

IO流的应用——Copy文件

(1)

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

//public void copyFile(String src,String dest){1,2,3,4步骤}

//一般写成public void copyFile(File src,File dest){2,3,4步骤}

//调用copyFile(new File(srcPath),new File(destPath));

public class复制文件 {

    public static void main(String[] args) throws IOException {

        //1)建立联系(源文件要存在,拷贝目的地文件可以不存在)

        File src=new File("F:/xp/test/下一层/java.txt");

        File dest=new File("F:/xp/test/java2.txt");    

        //2)选择流

        InputStream is=new FileInputStream(src);

        OutputStream os=new FileOutputStream(dest);    

        //3)文件拷贝循环+读取+写入

        byte[] flush=new byte[1024];

        int len=0;

        //读取

        while(-1!=(len=is.read(flush))){

            //写入

            os.write(flush, 0, len);

        }

        //强制刷出

        os.flush();    

        //4)关闭流(先打开后关闭)

        os.close();

        is.close();

    }

}

(2)

import java.io.*;

public class复制加强版 {

    //根据输入的路径拷贝

    static void copy(String src,String dest) throws IOException{

        copy(new File(src),new File(dest));

    }

    //根据传入的文件对象拷贝

    static void copy(File src,File dest) throws IOException{

            if(!src.exists()||!src.isFile()){

                return;

            }

            //2)选择流

            InputStream is=new FileInputStream(src);

            OutputStream os=new FileOutputStream(dest);

            //3)文件拷贝循环+读取+写入

            byte[] flush=new byte[1024];

            int len=0;

            //读取

            while(-1!=(len=is.read(flush))){

                //写入

                os.write(flush, 0, len);

            }

            //强制刷出

            os.flush();

            //4)关闭流(先打开后关闭)

            os.close();

            is.close();

    }

    public static void main(String[] args) {

        File src=new File("F:/xp/test/下一层/java.txt");

        File dest=new File("F:/xp/test/java2.txt");

        try {

            copy(src,dest);

        } catch (IOException e) {

            e.printStackTrace();

            System.out.println("文件拷贝失败!");

        }

    }

}

猜你喜欢

转载自www.cnblogs.com/xdzy/p/9467132.html