Java FileInputStream Copy copyFile(File sourceFile, File targetDir)

Here you can find the source of copyFile(File sourceFile, File targetDir)

Description

copy File

License

Open Source License

Declaration

public static boolean copyFile(File sourceFile, File targetDir) throws FileNotFoundException, IOException 

Method Source Code


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

public class Main {
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

    public static boolean copyFile(File sourceFile, File targetDir) throws FileNotFoundException, IOException {
        File targetFile = new File(targetDir, sourceFile.getName()); //target file's top file
        if (sourceFile.isDirectory()) { //Copy directory
            targetFile.mkdir();//from   ww w .j  a  va2s  .  co  m
            File[] dir = sourceFile.listFiles();
            for (int i = 0; i < dir.length; i++) {
                if (!copyFile(dir[i], targetFile)) {
                    return false;
                }
            }
            return true;
        } else { //Copy file
            FileInputStream fis = new FileInputStream(sourceFile);
            FileOutputStream fos = new FileOutputStream(targetFile);
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int c = 0;
            while ((c = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, c);
            }
            fis.close();
            fos.close();
            return true;
        }
    }

    public static boolean copyFile(File sourceFile, File targetDir, String targetFilename)
            throws FileNotFoundException, IOException {
        File targetFile = new File(targetDir, targetFilename); //target file's top file
        if (sourceFile.isDirectory()) { //Copy directory
            return false;
        } else { //Copy file
            FileInputStream fis = new FileInputStream(sourceFile);
            FileOutputStream fos = new FileOutputStream(targetFile);
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int c = 0;
            while ((c = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, c);
            }
            fis.close();
            fos.close();
            return true;
        }
    }
}

Related

  1. copyFile(File sourceFile, File destFile)
  2. copyFile(File sourceFile, File destFile)
  3. copyFile(File sourceFile, File destFile, boolean overwrite, boolean preserveLastModified)
  4. copyFile(File sourceFile, File destinationFile)
  5. copyFile(File sourceFile, File destinationFile)
  6. copyFile(File sourceFile, File targetDir)
  7. copyFile(File sourceFile, File targetFile)
  8. copyFile(File sourceFile, File targetFile)
  9. copyFile(File sourceFile, String newFileName)