Java FileInputStream Copy copyFile(String source, String destination)

Here you can find the source of copyFile(String source, String destination)

Description

Copies one file to another

License

Open Source License

Parameter

Parameter Description
source a parameter
destination a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void copyFile(String source, String destination) throws IOException 

Method Source Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    /**/*from ww w .  ja v  a 2  s.com*/
     * Copies one file to another
     * @param source
     * @param destination
     * @throws IOException
     */
    public static void copyFile(String source, String destination) throws IOException {
        copyFile(new File(source), new File(destination));
    }

    /**
     * Copies one file to another
     * @param source
     * @param destination
     * @throws IOException
     */
    public static void copyFile(File source, File destination) throws IOException {
        // some tests at first
        if (!source.exists()) {
            throw new IOException("No such file: " + source.getAbsolutePath());
        }
        if (!source.isFile()) {
            throw new IOException(source.getAbsolutePath() + " is not a file.");
        }
        if (!source.canRead()) {
            throw new IOException("Cannot read file: " + source.getAbsolutePath());
        }
        if (destination.isDirectory()) {
            throw new IOException("Cannot write to directory: " + destination.getAbsolutePath());
        }
        if (destination.exists() && !destination.canWrite()) {
            throw new IOException("File is not writeble: " + destination.getAbsolutePath());
        }

        // now, we are ready to copy
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(source);
            fos = new FileOutputStream(destination);

            byte[] buff = new byte[512];
            int bytesRead = 0;

            while ((bytesRead = fis.read(buff)) != -1) {
                fos.write(buff, 0, bytesRead);
            }
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }
}

Related

  1. copyFile(String resourceFimeName, String targetFileName)
  2. copyFile(String s, String s1)
  3. copyFile(String source, String dest)
  4. copyFile(String source, String destination)
  5. copyFile(String source, String destination)
  6. copyFile(String source, String destination)
  7. copyFile(String source, String target)
  8. copyFile(String source, String targetDirectory, String filesep)
  9. copyFile(String sourceFile, String destDir, String newFileName)