Java Copy File copyFilesFromDirToDir(String originalDir, String targetDir)

Here you can find the source of copyFilesFromDirToDir(String originalDir, String targetDir)

Description

copy Files From Dir To Dir

License

Apache License

Declaration

public static void copyFilesFromDirToDir(String originalDir, String targetDir) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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 copyFilesFromDirToDir(String originalDir, String targetDir) {
        // origin
        if (!originalDir.endsWith("/")) {
            originalDir = originalDir + "/";
        }/*  ww w.  j a  v  a 2s .  c  om*/

        //
        File originalFile = new File(originalDir);
        if (!originalFile.exists()) {
            System.out.println(originalFile.getAbsolutePath() + " does not exist.");
            return;
        }

        // target
        if (!targetDir.endsWith("/")) {
            targetDir = targetDir + "/";
        }

        //
        File targetFile = new File(targetDir);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        //
        String[] files = null;
        files = originalFile.list();

        for (String filename : files) {
            if (!filename.endsWith(".png"))
                continue;

            InputStream in = null;
            OutputStream out = null;
            try {
                in = new FileInputStream(originalDir + filename);
                out = new FileOutputStream(targetDir + filename);
                copyFile(in, out);
                in.close();
                in = null;
                out.flush();
                out.close();
                out = null;
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public static void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
    }
}

Related

  1. copyFiles(String[] sourceFiles, String toDir, boolean overwrite)
  2. copyFileSafe(File destinationFileName, File sourceFileName)
  3. copyFileSafe(File in, File out)
  4. copyFilesBinary(String srcFile, String destDir)
  5. copyFilesBinaryRecursively(File fromLocation, File toLocation, FileFilter fileFilter)
  6. copyFilesRecursive(File src, File dest)
  7. copyFilesToLocal(String destination, String source)