Example usage for org.apache.commons.io FileUtils copyFileToDirectory

List of usage examples for org.apache.commons.io FileUtils copyFileToDirectory

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils copyFileToDirectory.

Prototype

public static void copyFileToDirectory(File srcFile, File destDir) throws IOException 

Source Link

Document

Copies a file to a directory preserving the file date.

Usage

From source file:es.bsc.servicess.ide.PackagingUtils.java

/** Process the service element dependencies and make required actions for element package creation
 * //from   www .j av  a  2  s .  c o m
 * - Copy the jar libraries to the package libraries folder
 * - Copy class folders to the classes folder
 * - Create a zip file with the normal files and folders
 * - Other types do not need actions to do in the package creation phase
 * 
 * @param dependencies Array of dependencies to treat for the package
 * @param packName Name of the element package
 * @param packagesFolder Folder where element packages are created
 * @param classesFolder Folder where the classes of the packages must be copied
 * @param libFolder Folder where the libraries of the packages must be copied
 * @param myProgressMonitor Eclipse progress monitoring object. 
 * @throws CoreException
 * @throws InterruptedException
 */
private static void manageDependencies(List<Dependency> dependencies, String packName, IFolder packagesFolder,
        IFolder classesFolder, IFolder libFolder, IProgressMonitor myProgressMonitor)
        throws CoreException, InterruptedException {
    // File pack_folder = packages.getLocation().toFile();
    File libF = libFolder.getLocation().toFile();
    File classesF = classesFolder.getLocation().toFile();
    IFolder depsFolder = null;
    for (Dependency d : dependencies) {
        if (d.getType().equalsIgnoreCase(ProjectMetadata.JAR_DEP_TYPE)) {
            log.debug("Copying library " + d);
            File f = new File(d.getLocation());
            if (f != null) {
                try {
                    FileUtils.copyFileToDirectory(f, libF);
                    log.debug("File " + f.getAbsolutePath() + "has been copied to " + libF.getAbsolutePath());
                } catch (IOException e) {
                    log.debug(
                            "File " + f.getAbsolutePath() + "could not be copied to " + libF.getAbsolutePath());
                    e.printStackTrace();
                }
            } else {
                log.error("File " + d + "does not exists");
            }
        } else if (d.getType().equalsIgnoreCase(ProjectMetadata.CLASS_FOLDER_DEP_TYPE)) {
            File f = new File(d.getLocation());
            if (f != null && f.isDirectory()) {
                copyClassDirectory(f, classesF);
            } else {
                log.error("Folder " + d + "does not exists");
            }

        } else if (d.getType().equalsIgnoreCase(ProjectMetadata.FOLDER_DEP_TYPE)) {
            if (depsFolder == null) {
                depsFolder = packagesFolder.getFolder(packName + "_deps");
                depsFolder.create(true, true, myProgressMonitor);
            }
            File f = new File(d.getLocation());
            if (f != null && f.isDirectory()) {
                try {
                    File destFile = new File(
                            depsFolder.getLocation().toFile().getAbsolutePath() + File.separator + f.getName());
                    if (!destFile.exists() || !destFile.isDirectory()) {
                        destFile.mkdir();
                    }
                    FileUtils.copyDirectory(f, destFile);
                    log.debug("Folder " + f.getAbsolutePath() + "has been copied to "
                            + depsFolder.getLocation().toFile().getAbsolutePath());
                } catch (IOException e) {
                    log.error("Folder " + f.getAbsolutePath() + "could not be copied to "
                            + depsFolder.getLocation().toFile().getAbsolutePath(), e);
                }
            } else {
                log.error("Folder " + d + "does not exists");
            }

        } else if (d.getType().equalsIgnoreCase(ProjectMetadata.FILE_DEP_TYPE)) {
            if (depsFolder == null) {
                depsFolder = packagesFolder.getFolder(packName + "_deps");
                depsFolder.create(true, true, myProgressMonitor);
            }
            File f = new File(d.getLocation());
            if (f != null && f.isFile()) {
                try {
                    FileUtils.copyFileToDirectory(f, depsFolder.getLocation().toFile());
                    log.debug("File " + f.getAbsolutePath() + "has been copied to "
                            + depsFolder.getLocation().toFile().getAbsolutePath());
                } catch (IOException e) {
                    log.error("File " + f.getAbsolutePath() + "could not be copied to "
                            + depsFolder.getLocation().toFile().getAbsolutePath(), e);
                    e.printStackTrace();
                }
            } else {
                log.error("File " + d + "does not exists");
            }

        }
    }

    if (depsFolder != null) {
        IFile zip = packagesFolder.getFile(packName + "_deps.zip");
        createZip(zip, depsFolder, myProgressMonitor);
        depsFolder.delete(true, myProgressMonitor);
    }

}

From source file:kr.co.leem.system.FileSystemUtils.java

/**
 * ? .//from   w  w  w . j  a v a 2s  .  c  o  m
 *
 * @param srcFile ? ? .
 * @param destFile  ? .
 * @see FileUtils#copyFileToDirectory(File, File)
 */
public static void copyFileToDirectory(final String srcFile, final String destDir) {
    processIO(new IOCallback<Object>() {
        public Object doInProcessIO() throws IOException, NullPointerException {
            FileUtils.copyFileToDirectory(new File(srcFile), new File(destDir));
            return null;
        }
    });
}

From source file:de.uzk.hki.da.sb.Cli.java

/**
 * Copies the files listed in a file list to a single directory
 * /*from   w w w . j  a  v  a  2 s  .  c  o m*/
 * @param fileListFile The file list file
 * @return The path to the directory containing the files
 */
private String copySipContentToFolder(File fileListFile) {

    CliProgressManager progressManager = new CliProgressManager();

    String tempFolderName = getTempFolderName();

    String fileList = "";
    try {
        fileList = Utilities.readFile(fileListFile);
    } catch (Exception e) {
        logger.log("ERROR: Failed to read file " + fileListFile.getAbsolutePath(), e);
        System.out.println("Die Datei " + fileListFile.getAbsolutePath() + " konnte nicht gelesen werden.");
        return "";
    }

    fileList = fileList.replace("\r", "");
    if (!fileList.endsWith("\n"))
        fileList += "\n";

    long files = 0;
    for (int i = 0; i < fileList.length(); i++) {
        if (fileList.charAt(i) == '\n')
            files++;
    }
    progressManager.setTotalSize(files);

    File tempDirectory = new File(tempFolderName + File.separator + sipFactory.getName());
    tempDirectory.mkdirs();

    while (true) {
        int index = fileList.indexOf('\n');

        if (index >= 0) {
            String filepath = fileList.substring(0, index);
            fileList = fileList.substring(index + 1);

            File file = new File(filepath);
            if (!file.exists()) {
                logger.log("ERROR: File " + file.getAbsolutePath() + " is referenced in filelist, "
                        + "but does not exist");
                System.out.println("\nDie in der Dateiliste angegebene Datei " + file.getAbsolutePath()
                        + " existiert nicht.");
                FileUtils.deleteQuietly(tempDirectory);
                return "";
            }

            try {
                if (file.isDirectory())
                    FileUtils.copyDirectoryToDirectory(file, tempDirectory);
                else
                    FileUtils.copyFileToDirectory(file, tempDirectory);
                progressManager.copyFilesFromListProgress();
            } catch (IOException e) {
                logger.log("ERROR: Failed to copy file " + file.getAbsolutePath() + " to folder "
                        + tempDirectory.getAbsolutePath(), e);
                System.out.println("\nDie in der Dateiliste angegebene Datei " + file.getAbsolutePath()
                        + " konnte nicht kopiert werden.");
                FileUtils.deleteQuietly(tempDirectory);
                return "";
            }
        } else
            break;
    }

    return (tempDirectory.getAbsolutePath());
}

From source file:com.taobao.android.tools.TPatchTool.java

/**
 * process bundle files/* w  ww.j ava 2s .  c  o m*/
 *
 * @param newBundleFile
 * @param baseBundleFile
 * @param patchTmpDir
 * @param diffTxtFile
 */
public void processBundleFiles(File newBundleFile, File baseBundleFile, File patchTmpDir) throws Exception {
    String bundleName = FilenameUtils.getBaseName(newBundleFile.getName());
    File destPatchBundleDir = new File(patchTmpDir, bundleName);
    final File newBundleUnzipFolder = new File(newBundleFile.getParentFile(), bundleName);
    final File baseBundleUnzipFolder = new File(baseBundleFile.getParentFile(), bundleName);

    DiffType modifyType = getModifyType(newBundleFile.getName());

    long startTime = System.currentTimeMillis();

    logger.warning(">>> start to process bundle for patch " + bundleName + " >> difftype "
            + modifyType.toString() + " createALl:" + ((TpatchInput) input).createAll);

    if (modifyType == DiffType.ADD) {

        FileUtils.copyFileToDirectory(newBundleFile, patchTmpDir);

    } else if (((TpatchInput) input).createAll || (modifyType == DiffType.MODIFY)) {

        if (null != baseBundleFile && baseBundleFile.isFile() && baseBundleFile.exists()
                && !((TpatchInput) input).noPatchBundles.contains(baseBundleFile.getName().replace("_", ".")
                        .substring(3, baseBundleFile.getName().length() - 3))
                && input.diffBundleDex) {
            doBundlePatch(newBundleFile, baseBundleFile, patchTmpDir, bundleName, destPatchBundleDir,
                    newBundleUnzipFolder, baseBundleUnzipFolder);
        }
    }

    logger.warning(">>> fininsh to process bundle for patch " + bundleName + " >> difftype "
            + modifyType.toString() + " consume:" + (System.currentTimeMillis() - startTime));
}

From source file:com.isomorphic.maven.packaging.Distribution.java

/**
 * Extract the relevant contents from each file in the distribution.  Additionally creates ZIP/JAR
 * files from specified resources (e.g., javadoc).
 * //  w w w .ja v  a2  s . c om
 * @param to The directory to which each file should be extracted.
 * @throws IOException
 */
public void unpack(File to) throws IOException {

    outer: for (File file : files) {

        String ext = FilenameUtils.getExtension(file.getName()).toUpperCase();

        //copy uncompressed files to target, renaming as necessary per 'contents' configuration
        if (!"ZIP".equals(ext)) {
            for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) {
                AntPathMatcherFilter filter = filterEntry.getValue();
                if (filter.accept(file.getName())) {
                    File target = FileUtils.getFile(to,
                            ArchiveUtils.rewritePath(file.getName(), filterEntry.getKey()));
                    FileUtils.copyFile(file, target);
                    LOGGER.debug("Copied file '{}' to file '{}'", file.getName(), target.getAbsolutePath());
                    continue outer;
                }
            }
            FileUtils.copyFileToDirectory(file, new File(to, "lib"));
            continue outer;
        }

        //otherwise extract contents (again renaming / relocating contents as necessary)
        ZipFile zip = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zip.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) {
                AntPathMatcherFilter filter = filterEntry.getValue();
                if (filter.accept(entry.getName())) {
                    File target = FileUtils.getFile(to,
                            ArchiveUtils.rewritePath(entry.getName(), filterEntry.getKey()));
                    FileUtils.copyInputStreamToFile(zip.getInputStream(entry), target);
                    LOGGER.debug("Copied input stream to file '{}'", target.getAbsolutePath());
                }
            }
        }
        zip.close();
    }

    /*
     * Create any number of assemblies by dropping their resources here.
     * Each subdirectory will get zipped up and then deleted
     */
    File assembliesDir = new File(to, "assembly");

    @SuppressWarnings("unchecked")
    Collection<File> assemblies = CollectionUtils.arrayToList(assembliesDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File arg0) {
            return arg0.isDirectory();
        }
    }));
    for (File assembly : assemblies) {
        String name = FilenameUtils.getBaseName(assembly.getName());
        LOGGER.debug("Copying resources for assembly '{}'", name);
        ArchiveUtils.zip(assembly, FileUtils.getFile(assembliesDir, name + ".zip"));
        FileUtils.deleteQuietly(assembly);
    }

    LOGGER.debug("Repackaging Javadoc...");
    File docLib = new File(to, "doc/lib");

    //TODO these paths should probably all be stuck in some constant
    File client = FileUtils.getFile(to, "doc/api/client");
    if (client.exists()) {
        ArchiveUtils.jar(client, new File(docLib, "smartgwt-javadoc.jar"));
    }

    File server = FileUtils.getFile(to, "doc/api/server");
    if (server.exists()) {
        ArchiveUtils.jar(server, new File(docLib, "isomorphic-javadoc.jar"));
    }
}

From source file:com.uwsoft.editor.proxy.ProjectManager.java

public void importSpriteAnimationsIntoProject(final Array<FileHandle> fileHandles,
        ProgressHandler progressHandler) {
    if (fileHandles == null) {
        return;//from   w w w. j a v a 2s.co m
    }
    handler = progressHandler;

    ExecutorService executor = Executors.newSingleThreadExecutor();

    executor.execute(() -> {

        String newAnimName = null;

        String rawFileName = fileHandles.get(0).name();
        String fileExtension = FilenameUtils.getExtension(rawFileName);
        if (fileExtension.equals("png")) {
            Settings settings = new Settings();
            settings.square = true;
            settings.flattenPaths = true;

            TexturePacker texturePacker = new TexturePacker(settings);
            FileHandle pngsDir = new FileHandle(fileHandles.get(0).parent().path());
            for (FileHandle entry : pngsDir.list(Overlap2DUtils.PNG_FILTER)) {
                texturePacker.addImage(entry.file());
            }
            String fileNameWithoutExt = FilenameUtils.removeExtension(rawFileName);
            String fileNameWithoutFrame = fileNameWithoutExt.replaceAll("\\d*$", "");
            String targetPath = currentProjectPath + "/assets/orig/sprite-animations" + File.separator
                    + fileNameWithoutFrame;
            File targetDir = new File(targetPath);
            if (targetDir.exists()) {
                try {
                    FileUtils.deleteDirectory(targetDir);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            texturePacker.pack(targetDir, fileNameWithoutFrame);
            newAnimName = fileNameWithoutFrame;
        } else {
            for (FileHandle fileHandle : fileHandles) {
                try {
                    Array<File> imgs = getAtlasPages(fileHandle);
                    String fileNameWithoutExt = FilenameUtils.removeExtension(fileHandle.name());
                    String targetPath = currentProjectPath + "/assets/orig/sprite-animations" + File.separator
                            + fileNameWithoutExt;
                    File targetDir = new File(targetPath);
                    if (targetDir.exists()) {
                        FileUtils.deleteDirectory(targetDir);
                    }
                    for (File img : imgs) {
                        FileUtils.copyFileToDirectory(img, targetDir);
                    }
                    FileUtils.copyFileToDirectory(fileHandle.file(), targetDir);
                    newAnimName = fileNameWithoutExt;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (newAnimName != null) {
            ResolutionManager resolutionManager = facade.retrieveProxy(ResolutionManager.NAME);
            resolutionManager.resizeSpriteAnimationForAllResolutions(newAnimName, currentProjectInfoVO);
        }
    });
    executor.execute(() -> {
        changePercentBy(100 - currentPercent);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        handler.progressComplete();
    });
    executor.shutdown();
}

From source file:com.hp.test.framework.Reporting.Utlis.java

public static String replacelogs() throws IOException {
    URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();

    String path = location.toString();
    path = path.substring(6, path.indexOf("lib"));
    path = path.replace("%20", " ");
    String Logos_path = path + "ATU Reports/HTML_Design_Files/IMG";
    String Source_logs_path = path + "HTML_Design_Files/IMG";
    String Source_Framework_Logo_path = Source_logs_path + "/Framework_Logo.jpg";
    String Source_hp_logo_path = Source_logs_path + "/hp.png";
    String Source_reports_path = Source_logs_path + "/reports.jpg";
    File Target_dir = new File(Logos_path);
    File Source = new File(Source_Framework_Logo_path);
    FileUtils.copyFileToDirectory(Source, Target_dir);
    File Source_Reports = new File(Source_reports_path);
    FileUtils.copyFileToDirectory(Source_Reports, Target_dir);
    File Source_hp = new File(Source_hp_logo_path);
    FileUtils.copyFileToDirectory(Source_hp, Target_dir);
    return path;/*from  w ww . j a  va2  s . com*/
}

From source file:ddf.security.pdp.realm.xacml.processor.BalanaClientTest.java

private void testSetup() throws IOException {
    // Setup/*from www  .j av  a2s .co  m*/
    tempDir = folder.newFolder(TEMP_DIR_NAME);
    LOGGER.debug("Making directory: {}", tempDir.getPath());
    boolean dirExists = true;
    if (!tempDir.exists()) {
        dirExists = tempDir.mkdir();
    }
    if (dirExists) {
        File srcFile = new File(
                projectHome + File.separator + RELATIVE_POLICIES_DIR + File.separator + POLICY_FILE);
        FileUtils.copyFileToDirectory(srcFile, tempDir);
    }
}

From source file:com.o2d.pkayjava.editor.proxy.ProjectManager.java

public void importSpriteAnimationsIntoProject(final Array<FileHandle> fileHandles,
        ProgressHandler progressHandler) {
    if (fileHandles == null) {
        return;//from  w ww  .  ja  v a 2 s  . c  o  m
    }
    handler = progressHandler;

    ExecutorService executor = Executors.newSingleThreadExecutor();

    executor.execute(() -> {

        String newAnimName = null;

        String rawFileName = fileHandles.get(0).name();
        String fileExtension = FilenameUtils.getExtension(rawFileName);
        if (fileExtension.equals("png")) {
            Settings settings = new Settings();
            settings.square = true;
            settings.flattenPaths = true;

            TexturePacker texturePacker = new TexturePacker(settings);
            FileHandle pngsDir = new FileHandle(fileHandles.get(0).parent().path());
            for (FileHandle entry : pngsDir.list(Overlap2DUtils.PNG_FILTER)) {
                texturePacker.addImage(entry.file());
            }
            String fileNameWithoutExt = FilenameUtils.removeExtension(rawFileName);
            String fileNameWithoutFrame = fileNameWithoutExt.replaceAll("\\d*$", "");
            String targetPath = currentWorkingPath + "/" + currentProjectVO.projectName
                    + "/assets/orig/sprite-animations" + File.separator + fileNameWithoutFrame;
            File targetDir = new File(targetPath);
            if (targetDir.exists()) {
                try {
                    FileUtils.deleteDirectory(targetDir);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            texturePacker.pack(targetDir, fileNameWithoutFrame);
            newAnimName = fileNameWithoutFrame;
        } else {
            for (FileHandle fileHandle : fileHandles) {
                try {
                    Array<File> imgs = getAtlasPages(fileHandle);
                    String fileNameWithoutExt = FilenameUtils.removeExtension(fileHandle.name());
                    String targetPath = currentWorkingPath + "/" + currentProjectVO.projectName
                            + "/assets/orig/sprite-animations" + File.separator + fileNameWithoutExt;
                    File targetDir = new File(targetPath);
                    if (targetDir.exists()) {
                        FileUtils.deleteDirectory(targetDir);
                    }
                    for (File img : imgs) {
                        FileUtils.copyFileToDirectory(img, targetDir);
                    }
                    FileUtils.copyFileToDirectory(fileHandle.file(), targetDir);
                    newAnimName = fileNameWithoutExt;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (newAnimName != null) {
            ResolutionManager resolutionManager = facade.retrieveProxy(ResolutionManager.NAME);
            resolutionManager.resizeSpriteAnimationForAllResolutions(newAnimName, currentProjectInfoVO);
        }
    });
    executor.execute(() -> {
        changePercentBy(100 - currentPercent);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        handler.progressComplete();
    });
    executor.shutdown();
}

From source file:edu.ku.brc.specify.tools.FormDisplayer.java

/**
 * //ww  w.j  a v  a  2 s  .  c  o m
 */
private File checkForTemplateFiles(final String dstDirPath) {
    String templatePath = dstDirPath + File.separator + "schema_template.html";

    File templateFile = new File(templatePath); //$NON-NLS-1$
    if (templateFile.exists()) {
        return templateFile;
    }

    System.out.println(templatePath);
    try {
        File dstDirFile = new File(dstDirPath);
        if (!dstDirFile.exists()) {
            if (!dstDirFile.mkdirs()) {
                JOptionPane.showMessageDialog(null, "Error creating the site directory.");
            }
        }

        String zipFilePath = dstDirPath + File.separator + "site.zip";
        System.out.println("[" + zipFilePath + "]");

        String url = "http://files.specifysoftware.org/site.zip";
        HTTPGetter getter = new HTTPGetter();
        InputStream ins = getter.beginHTTPRequest(url);
        //DataInputStream  dins   = new DataInputStream(ins);
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(zipFilePath));
        byte[] bytes = new byte[4096];

        int totalBytes = 0;
        /*while (dins.available() > 0)
        {
        int len = dins.read(bytes);
        dos.write(bytes, 0, len);
        totalBytes += len;
        System.out.println(len+" / "+totalBytes);
        }*/
        int numBytes = 0;
        do {
            numBytes = ins.read(bytes);
            if (numBytes > 0) {
                dos.write(bytes, 0, numBytes);
                totalBytes += numBytes;
                System.out.println(numBytes);
            }

        } while (numBytes > 0);

        dos.flush();
        dos.close();
        //dins.close();

        System.out.println(totalBytes);

        File zipFile = new File(zipFilePath);
        System.out.println("zipFile: " + zipFile + " exists: " + zipFile.exists());

        List<File> unzippedFiles = ZipFileHelper.getInstance().unzipToFiles(zipFile);
        for (File unzippedFile : unzippedFiles) {
            FileUtils.copyFileToDirectory(unzippedFile, dstDirFile);
        }

        if (templateFile.exists()) {
            return templateFile;
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "You are missing the template that is needed to run this tool.");
    }
    return null;
}