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

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

Introduction

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

Prototype

public static void moveFile(File srcFile, File destFile) throws IOException 

Source Link

Document

Moves a file.

Usage

From source file:com.siberhus.tdfl.DataFileLoader.java

/**
 * /* www. jav  a 2  s. co m*/
 */
private void _load() {
    Resource sources[] = getSources();
    if (sources == null) {
        return;
    }

    DataFileReader reader = null;
    DataFileWriter successWriter = null, errorWriter = null;

    for (int i = 0; i < sources.length; i++) {
        Resource source = sources[i];
        try {
            String filename = source.getFilename();
            DataFileHandler fileHandler = null;
            for (DataFileHandler fh : dataFileHandlers) {
                if (fh.accept(filename)) {
                    fileHandler = fh;
                    break;
                }
            }
            if (fileHandler == null) {
                throw new DataFileLoaderException("No handler found for filename: " + filename);
            }

            reader = fileHandler.getReader();
            reader.setResource(source);
            successWriter = fileHandler.getSuccessWriter();
            if (successWriter != null) {
                Resource successResource = fileHandler.getSuccessResourceCreator().create(source);
                successWriter.setResource(successResource);
            }
            errorWriter = fileHandler.getErrorWriter();
            if (errorWriter != null) {
                Resource errorResource = fileHandler.getErrorResourceCreator().create(source);
                errorWriter.setResource(errorResource);
            }

            DataContext dataContext = new DataContext(this.attributes);
            dataContext.resource = source;
            dataContext.resourceNum = i;
            dataContext.startTime = new Date();
            if (dataFileProcessor instanceof DataContextAware) {
                ((DataContextAware) dataFileProcessor).setDataContext(dataContext);
            }
            try {
                doReadProcessWrite(dataContext, reader, successWriter, errorWriter);
                dataContext.exitStatus = ExitStatus.COMPLETED;
            } catch (Exception e) {
                dataContext.exitStatus = ExitStatus.FAILED;
                throw e;
            } finally {
                dataContext.finishTime = new Date();
                //may persist dataContext here

                if (reader != null)
                    try {
                        reader.close();
                    } catch (Exception e) {
                    }
                if (successWriter != null)
                    try {
                        successWriter.close();
                    } catch (Exception e) {
                    }
                if (errorWriter != null)
                    try {
                        errorWriter.close();
                    } catch (Exception e) {
                    }
            }

            if (shouldDeleteIfFinish) {
                logger.info("Deleting file " + source);
                source.getFile().delete();
            } else if (destination != null) {
                File destFile = destination.getFile();
                logger.debug("Moving file: " + source.getFile().getCanonicalPath() + " to file: "
                        + destFile.getCanonicalPath());
                if (resource.getFile().isDirectory()) {
                    FileUtils.moveFileToDirectory(source.getFile(), destFile, true);
                } else {
                    FileUtils.moveFile(source.getFile(), destFile);
                }
            }

        } catch (Exception e) {
            if (stopOnError) {
                if (e instanceof DataFileLoaderException) {
                    throw (DataFileLoaderException) e;
                } else {
                    throw new DataFileLoaderException(e.getMessage(), e);
                }
            } else {
                logger.error(e.getMessage(), e);
            }
        }
    } //for each resource
}

From source file:it.geosolutions.tools.compress.file.Extract.java

public static File extract(final File inFile, File destination, final boolean remove_source) throws Exception {

    if (inFile == null) {
        throw new IllegalArgumentException("Cannot open null file.");
    } else if (!inFile.exists()) {
        throw new FileNotFoundException(
                "The path does not match to an existent file into the filesystem: " + inFile);
    }/*from  w ww.  ja  v  a  2s .com*/
    if (destination == null || !destination.isDirectory() || !destination.canWrite()) {
        throw new IllegalArgumentException(
                "Extract: cannot write to a null or not writeable destination folder: " + destination);
    }

    // the new file-dir
    File end_file = null;

    final Matcher m = match(inFile.getName());
    if (m != null) {
        switch (getEnumType(inFile, true)) {
        case TAR:
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Input file is a tar file: " + inFile);
                LOGGER.info("Untarring...");
            }
            end_file = new File(destination, getName(m));
            if (end_file.equals(inFile)) {
                // rename inFile
                File tarFile = new File(inFile.getParent(), inFile.getName() + ".tar");
                FileUtils.moveFile(inFile, tarFile);
                TarReader.readTar(tarFile, end_file);
            } else {
                TarReader.readTar(inFile, end_file);
            }

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("tar extracted to " + end_file);
            }

            if (remove_source) {
                inFile.delete();
            }

            break;

        case BZIP2:
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Input file is a BZ2 compressed file.");

            // Output filename
            end_file = new File(destination, getName(m));

            // uncompress BZ2 to the tar file
            Extractor.extractBz2(inFile, end_file);

            if (remove_source) {
                inFile.delete();
            }

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("BZ2 uncompressed to " + end_file.getAbsolutePath());
            }

            end_file = extract(end_file, destination, true);
            break;
        case GZIP:
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Input file is a Gz compressed file.");

            // Output filename
            end_file = new File(destination, getName(m));

            // uncompress BZ2 to the tar file
            Extractor.extractGzip(inFile, end_file);

            if (remove_source)
                inFile.delete();

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("GZ extracted to " + end_file);
            }

            // recursion
            end_file = extract(end_file, destination, true);

            break;
        case ZIP:

            if (LOGGER.isInfoEnabled())
                LOGGER.info("Input file is a ZIP compressed file. UnZipping...");

            // preparing path to extract to
            end_file = new File(destination, getName(m));

            // run the unzip method
            Extractor.unZip(inFile, end_file);

            if (remove_source)
                inFile.delete();

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Zip file uncompressed to " + end_file);
            }

            // recursion
            end_file = extract(end_file, destination, remove_source);
            break;
        case NORMAL:

            end_file = inFile;

            if (LOGGER.isInfoEnabled())
                LOGGER.info("Working on a not compressed file.");
            break;
        default:
            throw new Exception("format file still not supported! Please try using bz2, gzip or zip");
        } // switch
    } // if match
    else {
        throw new Exception("File do not match regular expression");
    }

    /**
     * returning output file name
     */
    return end_file;
}

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);

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

    } else {//from  w  ww.j a v  a2  s . c  o  m
        throw new IllegalArgumentException(
                "srcPath must be a file, dstPath must be either a (non-existing) file or a directory");
    }
}

From source file:eu.udig.catalog.jgrass.operations.RenameMapAction.java

/**
 * Given the mapsetpath and the old and new mapname, the map is renamed with all its accessor files
 * /*w w w.  j a  v a 2  s  .c om*/
 * @param mapsetPath the mapset path.
 * @param oldMapName the old map name.
 * @param newMapName the new map name.
 * @throws IOException
 */
private void renameGrassRasterMap(String mapsetPath, String oldMapName, String newMapName) throws IOException {
    // list of files to remove
    String mappaths[] = JGrassCatalogUtilities.filesOfRasterMap(mapsetPath, oldMapName);

    // first delete the list above, which are just files
    for (int j = 0; j < mappaths.length; j++) {
        File filetorename = new File(mappaths[j]);
        if (filetorename.exists()) {
            File parentFile = filetorename.getParentFile();
            File renamedFile = new File(parentFile, newMapName);

            if (filetorename.isDirectory()) {
                FileUtils.moveDirectory(filetorename, renamedFile);
            } else if (filetorename.isFile()) {
                FileUtils.moveFile(filetorename, renamedFile);
            } else {
                throw new IOException("File type not defined");
            }

        }
    }
}

From source file:eu.openanalytics.rsb.component.DirectoryDepositHandler.java

public void handleResult(final MultiFilesResult result) throws IOException {
    final File resultFile = MultiFilesResult.zipResultFilesIfNotError(result);
    final File resultsDirectory = new File((File) result.getMeta().get(DEPOSIT_ROOT_DIRECTORY_META_NAME),
            Configuration.DEPOSIT_RESULTS_SUBDIR);

    final File outboxResultFile = new File(resultsDirectory,
            "result-" + FilenameUtils.getBaseName((String) result.getMeta().get(ORIGINAL_FILENAME_META_NAME))
                    + "." + FilenameUtils.getExtension(resultFile.getName()));

    FileUtils.deleteQuietly(outboxResultFile); // in case a similar result
                                               // already exists
    FileUtils.moveFile(resultFile, outboxResultFile);
    result.destroy();//from   w  ww.  j av  a2s  .c o m
}

From source file:com.jaxio.celerio.util.IOUtil.java

public void forceMove(File from, File to) {
    try {/*from w  w  w.  j  a va  2 s . c  om*/
        forceDelete(to);
        FileUtils.moveFile(from, to);
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.enonic.cms.web.webdav.DavResourceImpl.java

@Override
public void move(final DavResource target) throws DavException {
    if (!exists()) {
        throw new DavException(DavServletResponse.SC_NOT_FOUND);
    }//ww w. jav a  2s. co  m

    final File targetFile = ((DavResourceImpl) target).file;

    try {
        if (isCollection()) {
            FileUtils.moveDirectory(this.file, targetFile);
        } else {
            FileUtils.moveFile(this.file, targetFile);
        }
    } catch (final IOException e) {
        throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    }
}

From source file:com.commander4j.thread.AutoLabellerThread.java

public void run() {
    logger.debug("AutoLabeller Thread running");
    setSessionID(JUnique.getUniqueID());
    JDBUser user = new JDBUser(getHostID(), getSessionID());
    user.setUserId("interface");
    user.setPassword("interface");
    user.setLoginPassword("interface");
    Common.userList.addUser(getSessionID(), user);
    Common.sd.setData(getSessionID(), "silentExceptions", "Yes", true);

    Boolean dbconnected = false;/* w  w w .  ja  v  a2 s . com*/

    if (Common.hostList.getHost(hostID).isConnected(sessionID) == false) {

        dbconnected = Common.hostList.getHost(hostID).connect(sessionID, hostID);

    } else {
        dbconnected = true;
    }

    if (dbconnected) {

        JDBViewAutoLabellerPrinter alp = new JDBViewAutoLabellerPrinter(getHostID(), getSessionID());
        LinkedList<JDBViewAutoLabellerPrinter> autolabellerList = new LinkedList<JDBViewAutoLabellerPrinter>();

        int noOfMessages = 0;

        while (true) {

            JWait.milliSec(500);

            if (allDone) {
                if (dbconnected) {
                    Common.hostList.getHost(hostID).disconnect(getSessionID());
                }
                return;
            }

            autolabellerList.clear();
            autolabellerList = alp.getModifiedPrinterLines();
            noOfMessages = autolabellerList.size();

            if (noOfMessages > 0) {
                for (int x = 0; x < noOfMessages; x++) {
                    JWait.milliSec(100);

                    JDBViewAutoLabellerPrinter autolabview = autolabellerList.get(x);

                    messageProcessedOK = true;
                    messageError = "";

                    if (autolabview.getPrinterObj().isEnabled()) {
                        logger.debug("Line             =" + autolabview.getAutoLabellerObj().getLine());
                        logger.debug("Line Description =" + autolabview.getAutoLabellerObj().getDescription());
                        logger.debug("Printer ID       =" + autolabview.getPrinterObj().getPrinterID());
                        logger.debug("Printer Enabled  =" + autolabview.getPrinterObj().isEnabled());
                        logger.debug("Export Path      =" + autolabview.getPrinterObj().getExportRealPath());
                        logger.debug("Export Enabled   =" + autolabview.getPrinterObj().isExportEnabled());
                        logger.debug("Export Format    =" + autolabview.getPrinterObj().getExportFormat());
                        logger.debug("Direct Print     =" + autolabview.getPrinterObj().isDirectPrintEnabled());
                        logger.debug("Printer Type     =" + autolabview.getPrinterObj().getPrinterType());
                        logger.debug("Printer IP       =" + autolabview.getPrinterObj().getIPAddress());
                        logger.debug("Printer Port     =" + autolabview.getPrinterObj().getPort());
                        logger.debug("Process Order    =" + autolabview.getLabelDataObj().getProcessOrder());
                        logger.debug("Material         =" + autolabview.getLabelDataObj().getMaterial());
                        logger.debug("Module ID        =" + autolabview.getModuleObj().getModuleId());
                        logger.debug("Module Type      =" + autolabview.getModuleObj().getType());

                        if (autolabview.getPrinterObj().isExportEnabled()) {
                            String exportPath = JUtility.replaceNullStringwithBlank(
                                    JUtility.formatPath(autolabview.getPrinterObj().getExportRealPath()));
                            if (exportPath.equals("") == false) {
                                if (exportPath.substring(exportPath.length() - 1)
                                        .equals(File.separator) == false) {
                                    exportPath = exportPath + File.separator;
                                }
                            } else {
                                exportPath = Common.interface_output_path + "Auto Labeller" + File.separator;
                            }

                            String exportFilename = exportPath
                                    + JUtility.removePathSeparators(autolabview.getAutoLabellerObj().getLine())
                                    + "_"
                                    + JUtility.removePathSeparators(autolabview.getPrinterObj().getPrinterID())
                                    + "." + autolabview.getPrinterObj().getExportFormat();

                            String exportFilenameTemp = exportFilename + ".out";

                            logger.debug("Export Filename  =" + exportFilename);

                            /* ================CSV================ */

                            if (autolabview.getPrinterObj().getExportFormat().equals("CSV")) {
                                try {
                                    PreparedStatement stmt = null;
                                    ResultSet rs;
                                    String labelType = autolabview.getLabelDataObj().getLabelType();
                                    stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                                            .prepareStatement(
                                                    Common.hostList.getHost(getHostID()).getSqlstatements()
                                                            .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties"
                                                                    + "_" + labelType));
                                    stmt.setString(1, autolabview.getAutoLabellerObj().getLine());
                                    stmt.setString(2, autolabview.getPrinterObj().getPrinterID());
                                    stmt.setFetchSize(50);

                                    rs = stmt.executeQuery();

                                    logger.debug("Writing CSV");

                                    CSVWriter writer = new CSVWriter(new FileWriter(exportFilenameTemp),
                                            CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER,
                                            CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);

                                    writer.writeAll(rs, true);

                                    rs.close();

                                    stmt.close();

                                    writer.close();

                                    File fromFile = new File(exportFilenameTemp);
                                    File toFile = new File(exportFilename);

                                    FileUtils.deleteQuietly(toFile);
                                    FileUtils.moveFile(fromFile, toFile);

                                    fromFile = null;
                                    toFile = null;

                                } catch (Exception e) {
                                    messageProcessedOK = false;
                                    messageError = e.getMessage();
                                }
                            }

                            /* ================XML================ */

                            if (autolabview.getPrinterObj().getExportFormat().equals("XML")) {
                                try {
                                    PreparedStatement stmt = null;
                                    ResultSet rs;

                                    stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                                            .prepareStatement(Common.hostList.getHost(getHostID())
                                                    .getSqlstatements()
                                                    .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties"));
                                    stmt.setString(1, autolabview.getAutoLabellerObj().getLine());
                                    stmt.setString(2, autolabview.getPrinterObj().getPrinterID());
                                    stmt.setFetchSize(50);

                                    rs = stmt.executeQuery();
                                    ResultSetMetaData rsmd = rs.getMetaData();
                                    int colCount = rsmd.getColumnCount();

                                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                                    DocumentBuilder builder = factory.newDocumentBuilder();
                                    Document document = builder.newDocument();

                                    Element message = (Element) document.createElement("message");

                                    Element hostUniqueID = addElement(document, "hostRef",
                                            Common.hostList.getHost(getHostID()).getUniqueID());
                                    message.appendChild(hostUniqueID);

                                    Element messageRef = addElement(document, "messageRef",
                                            autolabview.getAutoLabellerObj().getUniqueID());
                                    message.appendChild(messageRef);

                                    Element messageType = addElement(document, "interfaceType",
                                            "Auto Labeller Data");
                                    message.appendChild(messageType);

                                    Element messageInformation = addElement(document, "messageInformation",
                                            "Unique ID=" + autolabview.getAutoLabellerObj().getUniqueID());
                                    message.appendChild(messageInformation);

                                    Element messageDirection = addElement(document, "interfaceDirection",
                                            "Output");
                                    message.appendChild(messageDirection);

                                    Element messageDate = addElement(document, "messageDate",
                                            JUtility.getISOTimeStampStringFormat(JUtility.getSQLDateTime()));
                                    message.appendChild(messageDate);

                                    if (rs.first()) {

                                        Element labelData = (Element) document.createElement("LabelData");

                                        Element row = document.createElement("Row");
                                        labelData.appendChild(row);
                                        for (int i = 1; i <= colCount; i++) {
                                            String columnName = rsmd.getColumnName(i);
                                            Object value = rs.getObject(i);
                                            Element node = document.createElement(columnName);
                                            node.appendChild(document.createTextNode(value.toString()));
                                            row.appendChild(node);
                                        }

                                        message.appendChild(labelData);

                                        document.appendChild(message);

                                        JXMLDocument xmld = new JXMLDocument();
                                        xmld.setDocument(document);

                                        // ===============================

                                        DOMImplementationLS DOMiLS = null;
                                        FileOutputStream FOS = null;

                                        // testing the support for DOM
                                        // Load and Save
                                        if ((document.getFeature("Core", "3.0") != null)
                                                && (document.getFeature("LS", "3.0") != null)) {
                                            DOMiLS = (DOMImplementationLS) (document.getImplementation())
                                                    .getFeature("LS", "3.0");

                                            // get a LSOutput object
                                            LSOutput LSO = DOMiLS.createLSOutput();

                                            FOS = new FileOutputStream(exportFilename);
                                            LSO.setByteStream((OutputStream) FOS);

                                            // get a LSSerializer object
                                            LSSerializer LSS = DOMiLS.createLSSerializer();

                                            // do the serialization
                                            LSS.write(document, LSO);

                                            FOS.close();
                                        }

                                        // ===============================

                                    }
                                    rs.close();
                                    stmt.close();

                                } catch (Exception e) {
                                    messageError = e.getMessage();
                                }

                            }

                            if (autolabview.getPrinterObj().getExportFormat().equals("LQF")) {

                            }
                        }

                        if (autolabview.getPrinterObj().isDirectPrintEnabled()) {

                        }

                    }

                    if (messageProcessedOK == true) {
                        autolabview.getAutoLabellerObj().setModified(false);
                        autolabview.getAutoLabellerObj().update();
                    } else {
                        logger.debug(messageError);
                    }

                    autolabview = null;
                }
            }
        }
    }
}

From source file:max.hubbard.bettershops.Shops.FileShop.java

public boolean setName(String name) {
    if (ShopManager.fromString(name) == null) {
        File old = file;// ww w .j  a  va2  s .c o  m
        String oldName = getName();
        File file1 = new File(file.getParentFile().getAbsolutePath(), name + ".yml");
        try {
            FileUtils.moveFile(file, file1);
            file = file1;
            old.delete();
            setObject("Name", name);

            ShopManager.names.remove(oldName);
            ShopManager.names.put(name, this);

            if (isNPCShop()) {
                if (Core.useCitizens()) {
                    ((CitizensShop) getNPCShop()).getNPC().setName("al" + name);
                } else {
                    ((NPCShop) getNPCShop()).entity.setCustomName("al" + name);
                }

            }
            if (isHoloShop()) {
                getHolographicShop().getNameLine().setText("al" + name);
            }

        } catch (IOException e) {
            return false;
        }

        loadMenus();
        return true;
    } else {
        return false;
    }
}

From source file:com.ephesoft.dcma.gwt.foldermanager.server.FolderManagerServiceImpl.java

@Override
public Boolean cutFiles(List<String> cutFilesList, String currentFolderPath) throws GWTException {
    for (String filePath : cutFilesList) {
        File srcFile = new File(filePath);
        String fileName = srcFile.getName();
        if (srcFile.exists()) {
            try {
                String newPathName = currentFolderPath + File.separator + srcFile.getName();
                File newFile = new File(newPathName);
                if (!newFile.exists()) {
                    if (srcFile.isFile()) {
                        FileUtils.moveFile(srcFile, newFile);
                    } else {
                        FileUtils.moveDirectory(srcFile, newFile);
                    }/*w w w  . j av  a  2  s.  c om*/
                } else {
                    throw new GWTException(
                            FolderManagementMessages.CANNOT_COMPLETE_CUT_PASTE_OPERATION_AS_THE_FILE_FOLDER
                                    + fileName + FolderManagementMessages.ALREADY_EXISTS);
                }
            } catch (IOException e) {
                LOGGER.error(
                        FolderManagementMessages.EXCEPTION_OCCURRED_WHILE_CUT_PASTE_OPERATION_COULD_NOT_COMPLETE_OPERATION
                                + e.getMessage());
                throw new GWTException(
                        FolderManagementMessages.EXCEPTION_OCCURRED_WHILE_CUT_PASTE_OPERATION_COULD_NOT_COMPLETE_OPERATION,
                        e);
            }
        } else {
            throw new GWTException(
                    FolderManagementMessages.EXCEPTION_OCCURRED_WHILE_CUT_PASTE_OPERATION_FILE_NOT_FOUND
                            + FolderManagementConstants.QUOTES + srcFile.getName()
                            + FolderManagementConstants.QUOTES);
        }
    }
    return true;
}