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

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

Introduction

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

Prototype

public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) throws IOException 

Source Link

Document

Moves a file to a directory.

Usage

From source file:net.orzo.lib.Files.java

public void moveFile(String srcPath, String dstPath) throws IOException {
    File src = new File(srcPath);
    File dst = new File(dstPath);

    if (src.isFile() && dst.getParentFile().isDirectory() && !dst.exists()) {
        FileUtils.moveFile(src, dst);/*from w w  w .j a  v a 2  s .c o m*/

    } else if (src.isFile() && dst.isDirectory()) {
        FileUtils.moveFileToDirectory(src, dst, false);

    } else {
        throw new IllegalArgumentException(
                "srcPath must be a file, dstPath must be either a (non-existing) file or a directory");
    }
}

From source file:com.diffplug.gradle.FileMisc.java

/**
 * Flattens a single directory (moves its children to be its peers, then deletes the given directory.
 * //from  w w  w . j a  v  a  2s.c  o m
 * ```
 * before:
 *     root/
 *        toFlatten/
 *           child1
 *           child2
 * 
 * flatten("root/toFlatten")
 * 
 * after:
 *     root/
 *        child1
 *        child2
 * ```
 */
public static void flatten(File dirToRemove) throws IOException {
    final File parent = dirToRemove.getParentFile();
    // move each child directory to the parent
    for (File child : FileMisc.list(dirToRemove)) {
        boolean createDestDir = false;
        if (child.isFile()) {
            FileUtils.moveFileToDirectory(child, parent, createDestDir);
        } else if (child.isDirectory()) {
            FileUtils.moveDirectoryToDirectory(child, parent, createDestDir);
        } else {
            throw new IllegalArgumentException("Unknown filetype: " + child);
        }
    }
    // remove the directory which we're flattening away
    FileMisc.forceDelete(dirToRemove);
}

From source file:fr.gael.dhus.database.DatabasePostInit.java

private boolean doIncomingRepopulate() {
    boolean force_relocate = Boolean.getBoolean("Archive.incoming.relocate");

    logger.info("Archives incoming relocate (Archive.incoming.relocate)" + " requested by user ("
            + force_relocate + ")");

    if (!force_relocate)
        return false;

    String incoming_path = System.getProperty("Archive.incoming.relocate.path",
            incomingManager.getIncomingBuilder().getRoot().getPath());

    // Force reset the counter.
    HierarchicalDirectoryBuilder output_builder = new HierarchicalDirectoryBuilder(new File(incoming_path),
            cfgManager.getArchiveConfiguration().getIncomingConfiguration().getMaxFileNo());

    Iterator<Product> products = productDao.getAllProducts();
    while (products.hasNext()) {
        Product product = products.next();
        boolean shared_path = false;

        // Copy the product path
        File old_path = new File(product.getPath().getPath());
        File new_path = null;

        // Check is same products are use for path and download
        if (product.getDownloadablePath().equals(old_path.getPath()))
            shared_path = true;/*from w  ww .jav  a2s  .c om*/

        if (incomingManager.isInIncoming(old_path)) {
            new_path = getNewProductPath(output_builder);
            try {
                logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath());
                FileUtils.moveToDirectory(old_path, new_path, true);

                File path = old_path;
                while (!incomingManager.isAnIncomingElement(path)) {
                    path = path.getParentFile();
                }
                FileUtils.cleanDirectory(path);
            } catch (IOException e) {
                logger.error("Cannot move directory " + old_path.getPath() + " to " + new_path.getPath(), e);
                logger.error("Aborting relocation process.");
                return false;
            }

            URL product_path = null;
            try {
                product_path = new File(new_path, old_path.getName()).toURI().toURL();
            } catch (MalformedURLException e) {
                logger.error("Unrecoverable error : aboting relocate.", e);
                return false;
            }
            product.setPath(product_path);
            // Commit this change
            productDao.update(product);
            searchService.index(product);
        }

        // copy the downloadable path
        if (product.getDownload().getPath() != null) {
            if (shared_path) {
                product.getDownload().setPath(product.getPath().getPath());
            } else {
                new_path = getNewProductPath(output_builder);
                old_path = new File(product.getDownload().getPath());
                try {
                    logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath());
                    FileUtils.moveFileToDirectory(old_path, new_path, false);
                } catch (IOException e) {
                    logger.error(
                            "Cannot move downloadable file " + old_path.getPath() + " to " + new_path.getPath(),
                            e);
                    logger.error("Aborting relocation process.");
                    return false;
                }
                product.getDownload().setPath(new File(new_path, old_path.getName()).getPath());
                // Commit this change
            }
            productDao.update(product);
        }

        // Copy Quicklooks
        new_path = null;
        if (product.getQuicklookFlag()) {
            old_path = new File(product.getQuicklookPath());
            if (new_path == null)
                new_path = output_builder.getDirectory();
            try {
                logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath());
                FileUtils.moveToDirectory(old_path, new_path, false);
            } catch (IOException e) {
                logger.error("Cannot move quicklook file " + old_path.getPath() + " to " + new_path.getPath(),
                        e);
                logger.error("Aborting relocation process.");
                return false;
            }
            File f = new File(new_path, old_path.getName());
            product.setQuicklookPath(f.getPath());
            product.setQuicklookSize(f.length());
            productDao.update(product);
        }
        // Copy Thumbnails in the same incoming path as quicklook
        if (product.getThumbnailFlag()) {
            old_path = new File(product.getThumbnailPath());
            if (new_path == null)
                new_path = output_builder.getDirectory();
            try {
                logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath());

                FileUtils.moveToDirectory(old_path, new_path, false);
            } catch (IOException e) {
                logger.error("Cannot move thumbnail file " + old_path.getPath() + " to " + new_path.getPath(),
                        e);
                logger.error("Aborting relocation process.");
                return false;
            }
            File f = new File(new_path, old_path.getName());
            product.setThumbnailPath(f.getPath());
            product.setThumbnailSize(f.length());
            productDao.update(product);
        }
    }
    // Remove unused directories
    try {
        cleanupIncoming(incomingManager.getIncomingBuilder().getRoot());
    } catch (Exception e) {
        logger.error("Cannot cleanup incoming folder", e);
    }
    return true;
}

From source file:de.uzk.hki.da.cb.RetrievePackagesHelper.java

/**
 * At the beginning the objects data are located under:
 * <pre>[workAreaRootPath]/[csn]/object-id/loadedAIPs/data</pre>
 * After they should be at//  w  ww .  j a  v a  2s .c o m
 * <pre>[workAreaRootPath]/[csn]/[id]/data</pre>
 * @param object
 * @throws IOException
 */
private void normalizeObject(Object object) throws IOException {

    String dataPath = wa.objectPath() + "/loadedAIPs/data/";
    String dataPathContents[] = new File(dataPath).list();

    if (dataPathContents == null)
        throw new RuntimeException("Listing files in " + dataPath + " failed!");
    for (int i = 0; i < dataPathContents.length; i++) {
        logger.debug("adding " + dataPathContents[i] + " to target location");
        if (new File(dataPath + dataPathContents[i]).isDirectory())
            FileUtils.moveDirectoryToDirectory(new File(dataPath + dataPathContents[i]), wa.dataPath().toFile(),
                    false);
        else
            FileUtils.moveFileToDirectory(new File(dataPath + dataPathContents[i]), wa.dataPath().toFile(),
                    false);
    }
}

From source file:net.pms.external.ExternalFactory.java

private static void purgeFiles() {
    File purge = new File("purge");
    String action = configuration.getPluginPurgeAction();

    if (action.equalsIgnoreCase("none")) {
        purge.delete();/*ww w  .j a v  a  2  s  . c o  m*/
        return;
    }

    try {
        try (FileInputStream fis = new FileInputStream(purge);
                BufferedReader in = new BufferedReader(new InputStreamReader(fis))) {
            String line;

            while ((line = in.readLine()) != null) {
                File f = new File(line);

                if (action.equalsIgnoreCase("delete")) {
                    f.delete();
                } else if (action.equalsIgnoreCase("backup")) {
                    FileUtils.moveFileToDirectory(f, new File("backup"), true);
                    f.delete();
                }
            }
        }
    } catch (IOException e) {
    }
    purge.delete();
}

From source file:de.uzk.hki.da.cb.UnpackAction.java

private void expandDirInto() {

    File[] files = wa.objectPath().toFile().listFiles();
    if (files.length == 1) {
        File[] folderFiles = files[0].listFiles();

        for (File f : folderFiles) {
            if (f.isFile()) {
                try {
                    FileUtils.moveFileToDirectory(f, wa.objectPath().toFile(), false);
                } catch (IOException e) {
                    throw new RuntimeException("couldn't move file " + f.getAbsolutePath() + " to folder "
                            + wa.objectPath().toFile(), e);
                }//from w w  w  .ja  va  2  s  . com
            }
            if (f.isDirectory()) {
                try {
                    FileUtils.moveDirectoryToDirectory(f, wa.objectPath().toFile(), false);
                } catch (IOException e) {
                    throw new RuntimeException("couldn't move folder " + f.getAbsolutePath() + " to folder "
                            + wa.objectPath().toFile(), e);
                }
            }
        }

        try {
            FolderUtils.deleteDirectorySafe(files[0]);
        } catch (IOException e) {
            throw new RuntimeException("couldn't delete folder " + files[0].getAbsolutePath());
        }
    }

}

From source file:com.yifanlu.PSXperiaTool.PSXperiaTool.java

private void generateOutput() throws IOException, InterruptedException, GeneralSecurityException,
        SignedJarBuilder.IZipEntryFilter.ZipAbortException {
    nextStep("Done processing, generating output.");
    String titleId = mProperties.getProperty("KEY_TITLE_ID");
    if (!mOutputDir.exists())
        mOutputDir.mkdir();/*w w  w .j  a  v  a 2 s . c o m*/
    File outDataDir = new File(mOutputDir, "/data/com.sony.playstation." + titleId + "/files/content");
    if (!outDataDir.exists())
        outDataDir.mkdirs();
    Logger.debug("Moving files around.");
    FileUtils.cleanDirectory(outDataDir);
    FileUtils.moveFileToDirectory(new File(mTempDir, "/" + titleId + ".zpak"), outDataDir, false);
    FileUtils.moveFileToDirectory(new File(mTempDir, "/image_ps_toc.bin"), outDataDir, false);
    Logger.verbose("Deleting config from temp directory.");
    FileUtils.deleteDirectory(new File(mTempDir, "/config"));
    File outApk = new File(mOutputDir, "/com.sony.playstation." + titleId + ".apk");

    ApkBuilder build = new ApkBuilder(mTempDir, outApk);
    build.buildApk();

    Logger.info("Done.");
    Logger.info("APK file: %s", outApk.getPath());
    Logger.info("Data dir: %s", outDataDir.getPath());

}

From source file:com.hangum.tadpole.rdb.core.dialog.driver.JDBCDriverManageDialog.java

/**
 *  ? //from w  w  w  .j ava2  s.  c om
 * 
 * @return
 */
private String startUploadReceiver() {
    receiver = new DiskFileUploadReceiver();
    final FileUploadHandler uploadHandler = new FileUploadHandler(receiver);
    uploadHandler.addUploadListener(new FileUploadListener() {
        public void uploadProgress(FileUploadEvent event) {
        }

        public void uploadFailed(FileUploadEvent event) {
            logger.error("file upload ", event.getException());
            //            MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Upload failed", "File upload fail.  " + event.getException().getMessage());
        }

        public void uploadFinished(FileUploadEvent event) {
            for (FileDetails file : event.getFileDetails()) {
                if (logger.isDebugEnabled())
                    logger.debug("===> " + file.getFileName()); //$NON-NLS-1$
            }

            String strFile = jdbc_dir;
            File[] arryFiles = receiver.getTargetFiles();
            for (File file : arryFiles) {
                try {
                    FileUtils.moveFileToDirectory(file, new File(jdbc_dir), true);

                    strFile += file.getName();
                } catch (Exception e) {
                    logger.error("driver move", e);
                    //                  MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Upload failed", "File upload fail.  " + e.getMessage());
                }
            }

            final String strTmpPaht = strFile;
            lvDriverFile.getList().getDisplay().asyncExec(new Runnable() {
                public void run() {
                    initDBFileList();

                    try {
                        JDBCDriverLoader.addJarFile(strTmpPaht);
                        setUploaded(true);
                    } catch (Exception e) {
                        logger.error("jar loading", e);
                    }
                }
            });
        }
    });

    return uploadHandler.getUploadUrl();
}

From source file:de.jwi.jfm.Folder.java

private String pasteClipboard(HttpSession session) throws OutOfSyncException, IOException {
    ClipBoardContent clipBoardContent = (ClipBoardContent) session.getAttribute("clipBoardContent");
    if (clipBoardContent == null) {
        return "nothing in clipboard";
    }/* ww w.ja v a  2 s  .  c  o m*/

    for (int i = 0; i < clipBoardContent.selectedfiles.length; i++) {
        File f = clipBoardContent.selectedfiles[i];
        File f1 = f.getParentFile();

        if (myFile.getCanonicalFile().equals(f1.getCanonicalFile())) {
            return "same folder";
        }
    }

    for (int i = 0; i < clipBoardContent.selectedfiles.length; i++) {
        File f = clipBoardContent.selectedfiles[i];

        if (clipBoardContent.contentType == ClipBoardContent.COPY_CONTENT) {
            if (f.isDirectory()) {
                FileUtils.copyDirectoryToDirectory(f, myFile);
            } else {
                FileUtils.copyFileToDirectory(f, myFile, true);
            }
        }
        if (clipBoardContent.contentType == ClipBoardContent.CUT_CONTENT) {
            if (f.isDirectory()) {
                FileUtils.moveDirectoryToDirectory(f, myFile, false);
            } else {
                FileUtils.moveFileToDirectory(f, myFile, false);
            }
        }
        if (clipBoardContent.contentType == ClipBoardContent.CUT_CONTENT) {
            session.removeAttribute("clipBoardContent");
        }
    }

    return "";
}

From source file:javaapplication3.SolidscapeDialog.java

private void submitBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitBtnActionPerformed
    if (validateForm()) {
        String buildPath = BPath.getText();
        buildName = new File(buildPath).getName();
        buildPath = buildPath.replace("\\", "\\\\");
        //File file = new File(buildPath);
        //buildName = file.getName();
        modelAmount = Integer.parseInt(numOfModels.getText());
        String comments = comment.getText();
        //hideErrorFields();            

        //now dealing with buildCost
        try {//from w ww .j  a  v a 2 s  .com
            Integer d = Integer.parseInt(days.getSelectedItem().toString());
            Integer h = Integer.parseInt(hours.getSelectedItem().toString());
            Integer m = Integer.parseInt(minutes.getSelectedItem().toString());
            buildTime = d + ":" + h + ":" + m;
            buildCost = Calculations.SolidscapeCost(d, h, m);
        } catch (Exception e) {
            errFree = true;
            e.printStackTrace();
        }
        //Checks if there were errors
        if (errFree) {
            try {
                //This is where we would add the call to the method that udpates things in completed Jobs
                //Updates project cost in pending
                SolidscapeMain.calc.BuildtoProjectCost(buildName, "Solidscape", buildCost);

                ResultSet res2 = SolidscapeMain.dba.searchPendingByBuildName(buildName);
                ArrayList list = new ArrayList();
                try {
                    while (res2.next()) {
                        list.add(res2.getString("buildName"));
                    }
                } catch (SQLException ex) {
                }

                Iterator itr = list.iterator();
                //Date date = Calendar.getInstance().getTime();
                //SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
                while (itr.hasNext()) {
                    ResultSet res3 = SolidscapeMain.dba.searchPendingByBuildName(itr.next().toString());
                    if (res3.next()) {
                        System.out.println("Now doing this shiz");
                        String ID = res3.getString("idJobs");
                        System.out.println(ID);
                        String Printer = res3.getString("printer");
                        String firstName = res3.getString("firstName");
                        String lastName = res3.getString("lastName");
                        String course = res3.getString("course");
                        String section = res3.getString("section");
                        String fileName = res3.getString("fileName");
                        System.out.println(fileName);

                        File newDir = new File(SolidscapeMain.getInstance().getSolidscapePrinted());
                        FileUtils.moveFileToDirectory(
                                new File(SolidscapeMain.getInstance().getSolidscapeToPrint() + fileName),
                                newDir, true);

                        String filePath = newDir.getAbsolutePath().replace("\\", "\\\\"); //Needs to be changed
                        String dateStarted = res3.getString("dateStarted");
                        String Status = "completed";
                        String Email = res3.getString("Email");
                        String Comment = res3.getString("comment");
                        String nameOfBuild = res3.getString("buildName");
                        double volume = Double.parseDouble(res3.getString("volume"));
                        double cost = Double.parseDouble(res3.getString("cost"));

                        SolidscapeMain.dba.insertIntoCompletedJobs(ID, Printer, firstName, lastName, course,
                                section, fileName, filePath, dateStarted, Status, Email, Comment, nameOfBuild,
                                volume, cost);
                        SolidscapeMain.dba.delete("pendingjobs", ID);
                        //In Open Builds, it should go back and change status to complete so it doesn't show up again if submitted
                    }
                }

                // if there is no matching record
                SolidscapeMain.dba.insertIntoSolidscape(buildName, modelAmount, ResolutionVar, buildTime,
                        comments, buildCost);
            } catch (IOException ex) {
                Logger.getLogger(SolidscapeDialog.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(SolidscapeDialog.class.getName()).log(Level.SEVERE, null, ex);
            }

            dispose();
        } else {
            System.out.println("ERRORS");
            JOptionPane.showMessageDialog(null,
                    "There were errors that prevented your build information from being submitted to the database. \nPlease consult the red error text on screen.");
        }
    }
}