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.osten.watermap.batch.FetchPCTWaypointsJob.java

private void unZipIt(File zipFile, File outputFolder) {
    byte[] buffer = new byte[1024];

    try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
        // get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            File newFile = new File(outputFolder.getAbsolutePath() + File.separator + fileName);

            log.log(Level.FINER, "file unzip : {0}", new Object[] { newFile.getAbsoluteFile() });

            // create all non existing folders else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            try (FileOutputStream fos = new FileOutputStream(newFile)) {
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }//  w  w  w .  ja v a2s.c  o  m
            }
            ze = zis.getNextEntry();

            // move newFile to data directory
            try {
                // have to delete first since FileUtils does not overwrite
                File destinationFile = new File(outputFolder + File.separator + newFile.getName());
                if (destinationFile.exists()) {
                    destinationFile.delete();
                }
                FileUtils.moveFileToDirectory(newFile, outputFolder, false);
            } catch (FileExistsException ioe) {
                log.warning(ioe.getLocalizedMessage());
            } catch (IOException ioe) {
                log.warning(ioe.getLocalizedMessage());
            }
        }

        // close the last entry
        zis.closeEntry();
    } catch (IOException e) {
        log.warning(e.getLocalizedMessage());
    }
}

From source file:edu.kit.dama.staging.services.processor.impl.DownloadZipper.java

@Override
public void performPostTransferProcessing(TransferTaskContainer pContainer) throws StagingProcessorException {
    LOGGER.debug("Zipping data");
    URL generatedFolder = pContainer.getGeneratedUrl();
    LOGGER.debug("Using target folder: {}", generatedFolder);

    try {/*from  ww  w  .j  a  va2  s.co m*/
        String zipFileName = CryptUtil.stringToSHA1(pContainer.getTransferInformation().getDigitalObjectId())
                + ".zip";
        URL targetZip = URLCreator.appendToURL(generatedFolder, zipFileName);
        LOGGER.debug("Zipping all data to file {}", targetZip);
        File targetFile = new File(targetZip.toURI());

        ITransferInformation info = pContainer.getTransferInformation();
        LOGGER.debug("Obtaining local folder for transfer with id {}", info.getTransferId());

        File localFolder = StagingService.getSingleton().getLocalStagingFolder(info,
                StagingService.getSingleton().getContext(info));
        File dataFolder = new File(
                FilenameUtils.concat(localFolder.getAbsolutePath(), Constants.STAGING_DATA_FOLDER_NAME));
        if (!dataFolder.exists()) {
            throw new IOException(
                    "Data folder " + dataFolder.getAbsolutePath() + " does not exist. Aborting zip operation.");
        }

        LOGGER.debug("Start zip operation using data input folder URL {}", dataFolder);
        ZipUtils.zip(new File(dataFolder.toURI()), targetFile);
        LOGGER.debug("Deleting 'data' folder content.");
        for (File f : new File(dataFolder.toURI()).listFiles()) {
            FileUtils.deleteQuietly(f);
        }
        LOGGER.debug("Moving result file {} to 'data' folder.", targetFile);
        FileUtils.moveFileToDirectory(targetFile, new File(dataFolder.toURI()), false);
        LOGGER.debug("Zip operation successfully finished.");
    } catch (IOException | URISyntaxException ex) {
        throw new StagingProcessorException("Failed to zip data", ex);
    }
}

From source file:ca.brood.softlogger.dataoutput.CSVOutputModule.java

private void updateFilename() throws Exception {
    String theFileName;//  ww  w. j  a v a2s .c o  m
    String oldFileName;
    Calendar cal = Calendar.getInstance();
    theFileName = csvSubdirectory + "/" + String.format("%1$tY%1$tm%1$td-%1$tH.%1$tM.%1$tS", cal) + "-"
            + m_OutputDevice.getDescription() + ".csv";

    try {
        if (!csvSubdirectory.equals(".")) {
            File csvDir = new File(csvSubdirectory);
            if (!csvDir.isDirectory()) {
                csvDir.mkdirs();
            }
        }
    } catch (Exception e) {
        log.error("Error - couldn't create the CSV destination directory: " + csvSubdirectory, e);
        throw e;
    }

    if (writer == null) {
        writer = new CSVFileWriter(theFileName);

        //Move all CSV files from csvSubdirectory to completedFileDirectory
        if (completedFileDirectory.length() > 0) {
            String[] extensions = new String[1];
            extensions[0] = "csv";
            File csvDir = new File(csvSubdirectory);
            File completedDir = new File(completedFileDirectory);

            try {
                Iterator<File> fileIter = FileUtils.iterateFiles(csvDir, extensions, false);

                while (fileIter.hasNext()) {
                    FileUtils.moveFileToDirectory(fileIter.next(), completedDir, true);
                }
            } catch (Exception e) {
                log.error("Couldn't move existing CSV files on startup.", e);
            }
        }

    } else {
        oldFileName = writer.getFilename();
        writer.setFilename(theFileName);

        if (!oldFileName.equalsIgnoreCase(theFileName)) {
            //File name has changed, move the old file if required
            try {
                if (completedFileDirectory.length() > 0) {
                    File completedDir = new File(completedFileDirectory);
                    if (!completedDir.isDirectory()) {
                        completedDir.mkdirs();
                    }
                    File oldFile = new File(oldFileName);
                    if (oldFile.exists()) {
                        String movedFileName = completedFileDirectory + "/" + oldFile.getName();
                        File movedFile = new File(movedFileName);

                        log.debug("Moving " + oldFileName + " to " + movedFileName);

                        FileUtils.moveFile(oldFile, movedFile);
                    }
                }
            } catch (Exception e) {
                log.error("Couldn't move the completed CSV file", e);
            }
        }
    }
}

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

private void moveSipDir() throws IOException {

    if (!wa.dataPath().toFile().mkdirs()) {
        throw new RuntimeException("couldn't create directory: " + wa.dataPath().toFile());
    }/*from www .j  a  va 2  s.c om*/

    File[] files = wa.sipFile().listFiles();
    if (files.length == 1) {
        File[] folderFiles = files[0].listFiles();
        for (File f : folderFiles) {
            if (f.isFile()) {
                try {
                    FileUtils.moveFileToDirectory(f, wa.dataPath().toFile(), false);
                } catch (IOException e) {
                    throw new RuntimeException("couldn't move file " + f.getAbsolutePath() + " to folder "
                            + wa.dataPath().toFile(), e);
                }
            }
            if (f.isDirectory()) {
                try {
                    FileUtils.moveDirectoryToDirectory(f, wa.dataPath().toFile(), false);
                } catch (IOException e) {
                    throw new RuntimeException("couldn't move folder " + f.getAbsolutePath() + " to folder "
                            + wa.dataPath().toFile(), e);
                }
            }
        }

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

}

From source file:guru.nidi.webjars.UseWebjarsMojo.java

private void move(File from, File to) throws IOException {
    getLog().debug("Moving " + from + " to " + to);
    final File[] roots = from.listFiles();
    if (roots != null) {
        for (final File root : roots) {
            if (root.isDirectory()) {
                final File target = new File(to, root.getName());
                getLog().debug("Moving directory" + root + " to " + target);
                FileUtils.moveDirectory(root, target);
            } else {
                getLog().debug("Moving file" + root + " to " + to);
                FileUtils.moveFileToDirectory(root, to, true);
            }/* w  w w. j av  a2 s.c om*/
        }
    }
}

From source file:es.sm2.openppm.front.threads.scheduler.MigrationJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {

    try {// w  ww.  j  av  a2s  . c  o m

        LogManager.getLog(getClass()).debug("START MIGRATION DOCUMENTS..");

        // Declare logic
        DocumentprojectLogic documentprojectLogic = new DocumentprojectLogic(null, null);

        // Get all documents
        //
        List<String> joins = new ArrayList<String>();
        joins.add(Documentproject.PROJECT);

        List<Documentproject> documents = documentprojectLogic.findAll(joins);

        if (ValidateUtil.isNotNull(documents)) {

            // Declare logic
            CompanyLogic companyLogic = new CompanyLogic();

            // Get companies
            List<Company> companies = companyLogic.findAll();

            if (ValidateUtil.isNotNull(companies)) {

                for (Company company : companies) {

                    LogManager.getLog(getClass()).debug("Migration for company: " + company.getIdCompany());

                    // Get settings
                    HashMap<String, String> settings = SettingUtil.getSettings(company);

                    // Root directory
                    String docFolder = SettingUtil.getString(settings, Settings.SETTING_PROJECT_DOCUMENT_FOLDER,
                            Settings.DEFAULT_PROJECT_DOCUMENT_FOLDER);

                    for (Documentproject document : documents) {

                        if (ValidateUtil.isNotNull(document.getName())) {

                            // Search document in root directory
                            //
                            File file = new File(docFolder + File.separator + document.getIdDocumentProject()
                                    + StringPool.UNDERLINE + document.getName());

                            if (file.exists()) {

                                // Get project
                                Project project = document.getProject();

                                // Search folder by project
                                String newDir = docFolder
                                        .concat(File.separator + StringUtils.formatting(project.getChartLabel())
                                                + StringPool.UNDERLINE + project.getIdProject());

                                File folderNewDir = new File(newDir);

                                // If not exists create
                                if (!folderNewDir.exists()) {
                                    folderNewDir.mkdir();
                                }

                                // Add subfolder
                                folderNewDir = new File(newDir.concat(File.separator + document.getType()));

                                // Rename file
                                //
                                String newName = document.getIdDocumentProject() + StringPool.UNDERLINE
                                        + (document.getName().lastIndexOf("\\") != -1
                                                ? StringUtils.formatting(document.getName()
                                                        .substring(document.getName().lastIndexOf("\\") + 1))
                                                : StringUtils.formatting(document.getName()));

                                File newFileRename = new File(docFolder + File.separator, newName);

                                if (file.renameTo(newFileRename)) {

                                    // Move file to directory
                                    FileUtils.moveFileToDirectory(newFileRename, folderNewDir, true);

                                    LogManager.getLog(getClass())
                                            .debug("Migration success: " + newFileRename.getAbsolutePath()
                                                    + " to " + folderNewDir.getAbsolutePath());
                                }
                            }
                        }
                    }
                }
            }
        }

        LogManager.getLog(getClass()).debug("END MIGRATION DOCUMENTS");
    } catch (Exception e) {
        ExceptionUtil.sendToLogger(LogManager.getLog(getClass()), e, null);
    }
}

From source file:it.greenvulcano.util.file.FileManager.java

/**
 * Move a file/directory on the local file system.<br>
 *
 * @param oldPath//  ww w. j a  v a 2  s.  c o  m
 *            Absolute pathname of the file/directory to be renamed
 * @param newPath
 *            Absolute pathname of the new file/directory
 * @param filePattern
 *            A regular expression defining the name of the files to be copied. Used only if
 *            srcPath identify a directory. Null or "" disable file filtering.
 * @throws Exception
 */
public static void mv(String oldPath, String newPath, String filePattern) throws Exception {
    File src = new File(oldPath);
    if (!src.isAbsolute()) {
        throw new IllegalArgumentException("The pathname of the source is NOT absolute: " + oldPath);
    }
    File target = new File(newPath);
    if (!target.isAbsolute()) {
        throw new IllegalArgumentException("The pathname of the destination is NOT absolute: " + newPath);
    }
    if (target.isDirectory()) {
        if ((filePattern == null) || filePattern.equals("")) {
            FileUtils.deleteQuietly(target);
        }
    }
    if (src.isDirectory()) {
        if ((filePattern == null) || filePattern.equals("")) {
            logger.debug("Moving directory " + src.getAbsolutePath() + " to " + target.getAbsolutePath());
            FileUtils.moveDirectory(src, target);
        } else {
            Set<FileProperties> files = ls(oldPath, filePattern);
            for (FileProperties file : files) {
                logger.debug("Moving file " + file.getName() + " from directory " + src.getAbsolutePath()
                        + " to directory " + target.getAbsolutePath());
                File finalTarget = new File(target, file.getName());
                FileUtils.deleteQuietly(finalTarget);
                if (file.isDirectory()) {
                    FileUtils.moveDirectoryToDirectory(new File(src, file.getName()), finalTarget, true);
                } else {
                    FileUtils.moveFileToDirectory(new File(src, file.getName()), target, true);
                }
            }
        }
    } else {
        if (target.isDirectory()) {
            File finalTarget = new File(target, src.getName());
            FileUtils.deleteQuietly(finalTarget);
            logger.debug("Moving file " + src.getAbsolutePath() + " to directory " + target.getAbsolutePath());
            FileUtils.moveFileToDirectory(src, target, true);
        } else {
            logger.debug("Moving file " + src.getAbsolutePath() + " to " + target.getAbsolutePath());
            FileUtils.moveFile(src, target);
        }
    }
}

From source file:edu.kit.dama.staging.services.processor.impl.IngestToDownloadProcessor.java

@Override
public void performPostTransferProcessing(TransferTaskContainer pContainer) throws StagingProcessorException {
    LOGGER.debug("Performing IngestToDownloadProcessor");
    IngestInformation ingest = (IngestInformation) pContainer.getTransferInformation();

    LOGGER.debug(" - Creating download entry");
    IAuthorizationContext ctx = new AuthorizationContext(new UserId(ingest.getOwnerId()),
            new GroupId(ingest.getGroupId()), Role.MEMBER);
    TransferClientProperties props = new TransferClientProperties();
    props.setStagingAccessPointId(accessPoint.getConfiguration().getUniqueIdentifier());
    DownloadInformation download;/*ww  w  .ja  va 2s .c  o  m*/
    try {
        download = DownloadInformationServiceLocal.getSingleton()
                .scheduleDownload(new DigitalObjectId(ingest.getDigitalObjectId()), props, ctx);
        LOGGER.debug(" - Download entry created. Setting status to DOWNLOAD_STATUS.PREPARING.");
        DownloadInformationServiceLocal.getSingleton().updateStatus(download.getId(),
                DOWNLOAD_STATUS.PREPARING.getId(), null, ctx);
        LOGGER.debug(" - Status successfully set. Starting moving data.");
    } catch (TransferPreparationException ex) {
        throw new StagingProcessorException(
                "Failed to create download for ingest with object id " + ingest.getDigitalObjectId(), ex);
    }

    LOGGER.debug(" - Obtaining data folder URL of ingest.");
    URL data = ingest.getDataFolderUrl();

    LOGGER.debug(" - Ingest data folder URL is: {}", data);

    AbstractStagingAccessPoint ingestAP = StagingConfigurationManager.getSingleton()
            .getAccessPointById(ingest.getAccessPointId());
    File baseFile = ingestAP.getLocalPathForUrl(data, ctx);
    LOGGER.debug(" - Ingest data path is: {}", baseFile);

    LOGGER.debug(" - Obtaining data folder URL of download.");
    File stagingPath = accessPoint.getLocalPathForUrl(download.getDataFolderUrl(), ctx);
    LOGGER.debug(" - Download data folder URL is: {}", stagingPath);

    try {
        LOGGER.debug("Moving {} to {}", baseFile, stagingPath);
        for (File f : baseFile.listFiles()) {
            LOGGER.debug(" - Moving file {}", f);
            if (f.isFile()) {
                FileUtils.moveFileToDirectory(f, stagingPath, false);
            } else if (f.isDirectory()) {
                FileUtils.moveDirectoryToDirectory(f, stagingPath, false);
            }
        }
        LOGGER.debug("All files successfully moved.");
    } catch (IOException ex) {
        throw new StagingProcessorException("Failed to move " + baseFile + " to " + stagingPath, ex);
    }

    if (doChgrp) {
        LOGGER.debug("GroupChange flag ist TRUE, changing ownership of data folder at {} to group {}",
                stagingPath, ingest.getGroupId());
        if (edu.kit.dama.util.SystemUtils.chgrpFolder(stagingPath, ingest.getGroupId())) {
            LOGGER.debug("Group ownership successfully changed.");
        } else {
            throw new StagingProcessorException("Failed to change group ownership for data folder "
                    + stagingPath + " to groupId {} " + ingest.getGroupId());
        }
    }

    LOGGER.debug("Successfully moved data to download path. Setting download to be ready.");
    DownloadInformationServiceLocal.getSingleton().updateStatus(download.getId(),
            DOWNLOAD_STATUS.DOWNLOAD_READY.getId(), null, ctx);
}

From source file:javaapplication3.ApprovePage.java

private void SubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SubmitButtonActionPerformed
    errorTxt1.setVisible(false);/*from   ww w. j a  va 2  s.c  o  m*/
    Double Volume = null;
    if (!volumeTextField.getText().equals("")) {
        try {
            Volume = Double.parseDouble(volumeTextField.getText());
        } catch (Exception ex) {
            error = true;
            errorTxt1.setText("*Numbers only");
            errorTxt1.setVisible(true);
        }
    } else {
        error = true;
        errorTxt1.setText("*Empty Field");
        errorTxt1.setVisible(true);
    }

    if (error == false) {
        dba.updatePendingJobVolume(ID, Volume);
        System.out.println(fileLoc);
        File newDir = new File(PendingJobs.inst.getDrive() + "\\ObjectLabPrinters\\" + printer + "\\ToPrint");
        try {
            FileUtils.moveFileToDirectory(new File(PendingJobs.inst.getSubmission() + "\\" + fileName), newDir,
                    true);
            dba.updatePendingJobFLocation(ID, fileName);
            PendingJobs.dba.approve(ID);
        } catch (SQLException ex) {
            Logger.getLogger(ApprovePage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileExistsException e) {
            FileUtils.deleteQuietly(new File(newDir.getAbsoluteFile() + fileName));
            newDir = new File(PendingJobs.inst.getDrive() + "\\ObjectLabPrinters\\" + printer + "\\ToPrint");
            try {
                FileUtils.moveFileToDirectory(new File(PendingJobs.inst.getSubmission() + "\\" + fileName),
                        newDir, true);
            } catch (IOException ex) {
                Logger.getLogger(ApprovePage.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException ex) {
            Logger.getLogger(ApprovePage.class.getName()).log(Level.SEVERE, null, ex);
        }
        dispose();
    }
}

From source file:javaapplication3.RejectDescription.java

private void SubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SubmitButtonActionPerformed
    // TODO add your handling code here:
    String Student = "Student name from database";
    String Error = ErrorText.getText();
    System.out.println("Sending Email");

    System.out.println(FileName);
    String[] splited = studentName.split(" ");
    String firstName = splited[0];
    String lastName = splited[1];
    ResultSet results = PendingJobs.dba.searchID("pendingjobs", firstName, lastName, FileName, dateSubmitted);
    try {/*from w  ww.  jav a 2 s  .co m*/
        if (results.next()) {
            Sender = new SendEmail(firstName, lastName, Error, FileName, results.getString("idJobs"));
            System.out.println(Error);
            Sender.Send();
            System.out.println(inst.getSubmission() + FileName);
            System.out.println(inst.getRejected() + FileName);
            File newDir = new File(inst.getRejected());
            FileUtils.moveFileToDirectory(new File(inst.getSubmission() + FileName), newDir, true);

            PendingJobs.dba.delete("pendingjobs", results.getString("idJobs"));
            JOptionPane.showMessageDialog(new JFrame(), "Email Sent Succesfully!");
        }
    } catch (SQLException | IOException ex) {
        Logger.getLogger(RejectDescription.class.getName()).log(Level.SEVERE, null, ex);
    }

    dispose();
}