集册 Java实例教程 尝试将文件“src”的第一个“amount”字节复制到“dst”,返回实际复制的字节数。

尝试将文件“src”的第一个“amount”字节复制到“dst”,返回实际复制的字节数。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

660
尝试将文件“ src”的第一个“数量”字节复制到“ dst”,返回实际复制的字节数。


//package com.nowjava;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;/** 时   代     Java  公  众  号 - nowjava.com 提供 **/

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;


public class Main {

    public static void main(String[] argv) throws Exception {

        File src = new File("Main.java");

        File dst = new File("Main.java");

        System.out.println(copy(src, dst));

    }

    /**
    NowJava.com - 时  代  Java 提供 
    **/

    /** 

     * Attempts to copy the first 'amount' bytes of file 'src' to 'dst',

     * returning the number of bytes actually copied.  If 'dst' already exists,

     * the copy may or may not succeed.

     * 

     * @param src the source file to copy

     * @param amount the amount of src to copy, in bytes

     * @param dst the place to copy the file

     * @return the number of bytes actually copied.  Returns 'amount' if the

     *  entire requested range was copied.

     */

    public static int copy(File src, int amount, File dst) {

        final int BUFFER_SIZE = 1024;

        int amountToRead = amount;

        InputStream in = null;

        OutputStream out = null;

        try {

            //I'm not sure whether buffering is needed here.  It can't hurt.

            in = new BufferedInputStream(new FileInputStream(src));

            out = new BufferedOutputStream(new FileOutputStream(dst));

            byte[] buf = new byte[BUFFER_SIZE];

            while (amountToRead > 0) {

                int read = in.read(buf, 0,

                        Math.min(BUFFER_SIZE, amountToRead));

                if (read == -1)

                    break;

                amountToRead -= read;

                out.write(buf, 0, read);

            }

        } catch (IOException e) {

        } finally {

            if (in != null)

                try {

                    in.close();

                } catch (IOException e) {

                }

            if (out != null) {

                try {

                    out.flush();

                } catch (IOException e) {

                }

                try {

                    out.close();

                } catch (IOException e) {

                }

            }

        }

        return amount - amountToRead;

    }


    
展开阅读全文