Seven ways to copy files in java

Article directory

1. Copy files by byte stream

  /**
     * Copy files by byte stream
     * @param sourcePath Source file path
     * @param targetPath Destination file path
     */
    public static void copyFileByStream(String sourcePath,String targetPath){
        //Source file path
        File source = new File(sourcePath);
        //Destination file path
        File target = new File(targetPath);

        //Cannot copy if source file does not exist
        if(!source.exists()){
            return;
        }
        //Create if the destination file directory does not exist
        if(!target.getParentFile().exists()){
            target.getParentFile().mkdirs();
        }

        try {
            //Copy files
            InputStream inputStream = new FileInputStream(source);
            OutputStream outputStream = new FileOutputStream(target);
            int temp = 0;
            //Read 1024 bytes at a time
            byte[] data = new byte[1024];
            //Save the data read each time to the byte array, and return the number of reads
            while ((temp = inputStream.read(data)) != -1){
                //Output array
                outputStream.write(data,0,temp);
            }

            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2. File copy through character stream

Only text files can be copied using character streams

    /**
     * Copy files by character stream
     *
     * @param sourcePath Source file path
     * @param targetPath Destination file path
     */
    public static void copyFileByReaderAndWriter(String sourcePath, String targetPath) {
        //Source file path
        File source = new File(sourcePath);
        //Destination file path
        File target = new File(targetPath);

        //Cannot copy if source file does not exist
        if (!source.exists()) {
            return;
        }
        //Create if the destination file directory does not exist
        if (!target.getParentFile().exists()) {
            target.getParentFile().mkdirs();
        }

        FileReader in = null;
        FileWriter out = null;
        try {
            //Character input stream and character output stream
            in = new FileReader(source);
            out = new FileWriter(target);

            char[] c = new char[1024];
            int temp = 0;
            //1024 characters at a time
            while ((temp = in.read(c)) != -1) {
                //output to a file
                out.write(c, 0, temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //Closed flow
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

3. File copy through byte buffer stream

/**
     * Copy files by byte buffer stream
     *
     * @param sourcePath Source file path
     * @param targetPath Destination file path
     */
    public static void copyFileByBuffered(String sourcePath, String targetPath){
        //Source file path
        File source = new File(sourcePath);
        //Destination file path
        File target = new File(targetPath);

        //Cannot copy if source file does not exist
        if (!source.exists()) {
            return;
        }
        //Create if the destination file directory does not exist
        if (!target.getParentFile().exists()) {
            target.getParentFile().mkdirs();
        }

        InputStream in = null;
        OutputStream out = null;
        try {
            //Byte buffered input stream and byte buffered output stream
            in = new BufferedInputStream(new FileInputStream(source));
            out = new BufferedOutputStream(new FileOutputStream(target));

            byte[] b = new byte[1024];
            int temp = 0;
            //Read a byte array of 1024 at a time
            while((temp = in.read(b)) != -1){
                //output to a file
                out.write(b,0,temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //Closed flow
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

4. Copy files through character buffer stream

Character buffer streams can only read text files

 /**
     * Copy files by character buffer stream
     *
     * @param sourcePath Source file path
     * @param targetPath Destination file path
     */
    public static void copyFileByBufferedChar(String sourcePath, String targetPath){
        //Source file path
        File source = new File(sourcePath);
        //Destination file path
        File target = new File(targetPath);

        //Cannot copy if source file does not exist
        if (!source.exists()) {
            return;
        }
        //Create if the destination file directory does not exist
        if (!target.getParentFile().exists()) {
            target.getParentFile().mkdirs();
        }

        BufferedReader in = null;
        BufferedWriter out = null;

        try {
            //Character buffered input stream and character buffered output stream
            in = new BufferedReader(new FileReader(source));
            out = new BufferedWriter(new FileWriter(target));

            //Read file (one line at a time)
            String temp = null;
            while((temp = in.readLine()) != null){
                //output to a file
                out.write(temp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //Closed flow
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

5. Copy files through JAVA NIO indirect buffer

   /**
     * Copying files through JAVA NIO indirect buffer
     *
     * @param sourcePath Source file path
     * @param targetPath Destination file path
     */
    public static void copyFileByChannel(String sourcePath, String targetPath) {
        FileChannel outChannel = null;
        FileChannel inChannel = null;

        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(sourcePath);
            fos = new FileOutputStream(targetPath);

            //Access channel
            inChannel = fis.getChannel();
            outChannel = fos.getChannel();

            //Allocate buffer of specified size
            ByteBuffer buf = ByteBuffer.allocate(1024);

            while (inChannel.read(buf) != -1) {
                //Convert to read data mode
                buf.flip();
                //Write to disk
                outChannel.write(buf);
                //Clear buffer
                buf.clear();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //Closed flow
            try {
                if (outChannel != null) {
                    outChannel.close();
                }
                if (inChannel != null) {
                    inChannel.close();
                }
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

6. Copy files through JAVA NIO direct buffer

/**
     * Copying files (memory mapping files) through JAVA NIO direct buffer
     *
     * @param sourcePath Source file path
     * @param targetPath Destination file path
     */
    public static void copyFileByChannelBufferd(String sourcePath, String targetPath) {
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            //Get channel, StandardOpenOption.READ means readable, StandardOpenOption.WRITE means writable, StandardOpenOption.CREATE means can be created
            inChannel = FileChannel.open(Paths.get(sourcePath), StandardOpenOption.READ);
            outChannel = FileChannel.open(Paths.get(targetPath), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);

            //Create memory map file
            MappedByteBuffer inMapped = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
            MappedByteBuffer outMapped = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());

            //Direct operation memory mapping file
            byte[] buf = new byte[inMapped.limit()];
            inMapped.get(buf);
            outMapped.put(buf);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //Closed flow
            try {
                if (outChannel != null) {
                    outChannel.close();
                }
                if (inChannel != null) {
                    inChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

7. transfer copy file through JAVA NIO channel

One way

 /**
     *  Transfer copy files through JAVA NIO channel
     *
     * @param sourcePath Source file path
     * @param targetPath Destination file path
     */
    public static void copyFileByChannelTransfer(String sourcePath, String targetPath) {
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            //Access channel
            inChannel = FileChannel.open(Paths.get(sourcePath), StandardOpenOption.READ);
            outChannel = FileChannel.open(Paths.get(targetPath),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);

            inChannel.transferTo(0,inChannel.size(),outChannel);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //Closed flow
            try {
                if (outChannel != null) {
                    outChannel.close();
                }
                if (inChannel != null) {
                    inChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Mode two

 /**
     *  Transfer copy files through JAVA NIO channel
     *
     * @param sourcePath Source file path
     * @param targetPath Destination file path
     */
    public static void copyFileByChannelTransfer2(String sourcePath, String targetPath) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            fis = new FileInputStream(sourcePath);
            fos = new FileOutputStream(targetPath);

            //Access channel
            inChannel = fis.getChannel();
            outChannel = fos.getChannel();

            inChannel.transferTo(0,inChannel.size(),outChannel);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //Closed flow
            try {
                if (outChannel != null) {
                    outChannel.close();
                }
                if (inChannel != null) {
                    inChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Use example

        String source = "e:\\demo\\Emperor of heaven.txt";
        String target = "e:\\demo\\";
        long time1 = System.currentTimeMillis();
        copyFileByStream(source, target + "1.txt");
        System.out.println("It takes time to copy files by byte stream:" + (System.currentTimeMillis() - time1));

        long time2 = System.currentTimeMillis();
        copyFileByReaderAndWriter(source, target + "2.txt");
        System.out.println("It takes time to copy files through character stream:" + (System.currentTimeMillis() - time2));

        long time3 = System.currentTimeMillis();
        copyFileByBuffered(source, target + "3.txt");
        System.out.println("It takes time to copy files through byte buffer stream:" + (System.currentTimeMillis() - time3));

        long time4 = System.currentTimeMillis();
        copyFileByBufferedChar(source, target + "4.txt");
        System.out.println("It takes time to copy files through character buffer stream:" + (System.currentTimeMillis() - time4));

        long time5 = System.currentTimeMillis();
        copyFileByChannel(source, target + "5.txt");
        System.out.println("adopt JAVA NIO Channel (indirect buffer) takes time to copy files:" + (System.currentTimeMillis() - time5));

        long time6 = System.currentTimeMillis();
        copyFileByChannelBufferd(source, target + "6.txt");
        System.out.println("adopt JAVA NIO Channel (direct buffer) takes time to copy files:" + (System.currentTimeMillis() - time6));

        long time7 = System.currentTimeMillis();
        copyFileByChannelTransfer(source, target + "7.txt");
        System.out.println("adopt JAVA NIO It takes time for channel transmission to copy files:" + (System.currentTimeMillis() - time7));

        long time8 = System.currentTimeMillis();
        copyFileByChannelTransfer(source, target + "8.txt");
        System.out.println("adopt JAVA NIO Channel transfer 2 takes time to copy files:" + (System.currentTimeMillis() - time8));

Through the test, it is found that using JAVA NIO channel transmission, JAVA NIO channel direct buffer and byte buffer stream to copy files is the most efficient

83 original articles published, 93 praised, 210000 visitors+
Private letter follow

Tags: Java

Posted on Mon, 03 Feb 2020 09:17:23 -0500 by released