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:org.specrunner.htmlunit.result.WritablePage.java

/**
 * Move files/directory.//from  w w  w . j  a v a  2 s.  c o m
 * 
 * @param from
 *            The original file/directory.
 * @param to
 *            The target file/directory.
 * @throws IOException
 *             On move errors.
 * @throws ResultException
 *             On action errors.
 */
protected void move(File from, File to) throws IOException, ResultException {
    if (!from.exists()) {
        if (UtilLog.LOG.isInfoEnabled()) {
            UtilLog.LOG.debug("File/Dir " + from + " not exists.");
        }
        return;
    }
    if (to.exists()) {
        if (!to.delete()) {
            throw new ResultException("Could not remove resources '" + to + "'.");
        }
    }
    if (UtilLog.LOG.isDebugEnabled()) {
        UtilLog.LOG.debug("Moving " + from + " to " + to + ".");
    }
    if (from.isDirectory()) {
        FileUtils.moveDirectory(from, to);
    } else {
        FileUtils.moveFile(from, to);
    }
}

From source file:org.specrunner.webdriver.result.WritableWebDriver.java

/**
 * Move files/directory./* www  .  j av a  2  s.com*/
 * 
 * @param from
 *            The original file/directory.
 * @param to
 *            The target file/directory.
 * @throws IOException
 *             On move errors.
 * @throws ResultException
 *             On action errors.
 */
protected void move(File from, File to) throws IOException, ResultException {
    if (to.exists()) {
        if (!to.delete()) {
            throw new ResultException("Could not remove resources '" + to + "'.");
        }
    }
    if (UtilLog.LOG.isDebugEnabled()) {
        UtilLog.LOG.debug("Moving " + from + " to " + to + ".");
    }
    if (from.isDirectory()) {
        FileUtils.moveDirectory(from, to);
    } else {
        FileUtils.moveFile(from, to);
    }
}

From source file:org.spout.api.util.config.migration.ConfigurationMigrator.java

/**
 * Perform migration of the configuration this object was constructed with
 * If migration was not necessary ({@link #shouldMigrate()} returned false), the method invocation will be considered successful.
 * If {@link #configuration} is a {@link org.spout.api.util.config.FileConfiguration}, the file the configuration vas previously stored in will be
 * moved to (file name).old as a backup of the data before migration
 *
 * @throws MigrationException if the configuration could not be successfully migrated
 *///from   w w w .  j av  a2  s  .  co m
public void migrate() throws MigrationException {
    if (!shouldMigrate()) {
        return;
    }

    if (configuration instanceof FileConfiguration) {

        File oldFile = ((FileConfiguration) configuration).getFile();
        try {
            FileUtils.moveFile(oldFile, new File(oldFile.getAbsolutePath() + ".old"));
        } catch (IOException e) {
            throw new MigrationException(e);
        }
    }

    for (Map.Entry<String[], MigrationAction> entry : getMigrationActions().entrySet()) {
        final ConfigurationNode existingNode = configuration.getNode(entry.getKey());
        final Object existing = existingNode.getValue();
        existingNode.remove();
        if (existing == null || entry.getValue() == null) {
            continue;
        }
        final String[] newKey = entry.getValue().convertKey(entry.getKey());
        final Object newValue = entry.getValue().convertValue(existing);
        configuration.getNode(newKey).setValue(newValue);
    }
    try {
        configuration.save();
    } catch (ConfigurationException e) {
        throw new MigrationException(e);
    }
}

From source file:org.spout.engine.filesystem.WorldFiles.java

public static boolean savePlayerData(SpoutPlayer player) {
    File playerDir = new File(Spout.getEngine().getDataFolder().toString(), "players");
    //Save data to temp file first
    String fileName = player.getName() + ".dat";
    String tempName = fileName + ".temp";
    File playerData = new File(playerDir, tempName);
    if (!playerData.exists()) {
        try {//from  w  w w .j  a v a  2  s .c o  m
            playerData.createNewFile();
        } catch (Exception e) {
            Spout.getLogger().log(Level.SEVERE, "Error creating player data for " + player.getName(), e);
        }
    }
    PlayerSnapshot snapshot = new PlayerSnapshot(player);
    CompoundTag playerTag = saveEntity(snapshot);
    NBTOutputStream os = null;
    try {
        os = new NBTOutputStream(new DataOutputStream(new FileOutputStream(playerData)), false);
        os.writeTag(playerTag);
    } catch (IOException e) {
        Spout.getLogger().log(Level.SEVERE, "Error saving player data for " + player.getName(), e);
        playerData.delete();
        return false;
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException ignore) {
            }
        }
    }
    try {
        //Move the temp data to final location
        File finalData = new File(playerDir, fileName);
        if (finalData.exists()) {
            finalData.delete();
        }
        FileUtils.moveFile(playerData, finalData);
        return true;
    } catch (IOException e) {
        Spout.getLogger().log(Level.SEVERE, "Error saving player data for " + player.getName(), e);
        playerData.delete();
        return false;
    }
}

From source file:org.spoutcraft.client.gui.mainmenu.MainMenu.java

private static String getSplashText() {
    BufferedReader br = null;//from   w ww  .  jav  a2 s .c o  m
    try {
        if (splashes.size() == 0) {
            File splashTextFile = new File(FileUtil.getConfigDir(), "splashes.txt");
            //refresh every day
            if (!splashTextFile.exists() || (System.currentTimeMillis()
                    - splashTextFile.lastModified() > (1L * 24 * 60 * 60 * 1000))) {
                URL test = new URL("http://cdn.spout.org/splashes.txt");
                HttpURLConnection urlConnect = (HttpURLConnection) test.openConnection();
                System.setProperty("http.agent", "");
                urlConnect.setRequestProperty("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");

                File temp = new File(FileUtil.getConfigDir(), "splashes.temp");
                if (temp.exists()) {
                    temp.delete();
                }
                FileUtils.copyInputStreamToFile(urlConnect.getInputStream(), temp);
                FileUtils.moveFile(temp, splashTextFile);
            }
            br = new BufferedReader(new InputStreamReader(new FileInputStream(splashTextFile)));
            String line;
            splashes.clear();
            while ((line = br.readLine()) != null) {
                splashes.add(line);
            }
            br.close();
        }
        return splashes.get((new Random()).nextInt(splashes.size()));
    } catch (Exception e) {
        return "I <3 Spout";
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:org.spoutcraft.client.io.DownloadAssets.java

public static void importOldConfig() {
    // This method must execute before constructores creates blank ones.
    String pathToOldConfig;/*from   w ww. ja va2 s . com*/
    File jar = new File(
            CustomTextureManager.class.getProtectionDomain().getCodeSource().getLocation().getFile());
    try {
        pathToOldConfig = jar.getCanonicalPath();
    } catch (IOException e1) {
        pathToOldConfig = jar.getAbsolutePath();
    }
    try {
        pathToOldConfig = URLDecoder.decode(pathToOldConfig, "UTF-8");
    } catch (java.io.UnsupportedEncodingException ignore) {
    }

    File relative = new File(pathToOldConfig + "/../../../../../.spoutcraft/config");

    try {
        pathToOldConfig = relative.getCanonicalPath();
    } catch (IOException e) {
        pathToOldConfig = relative.getAbsolutePath();
    }

    try {
        if (!(new File(FileUtil.getConfigDir() + "/bindings.yml").exists())) {
            File newFile = new File(FileUtil.getConfigDir() + "/bindings.yml");
            File oldFile = new File(pathToOldConfig + "/bindings.yml");
            if (oldFile.exists()) {
                FileUtils.moveFile(oldFile, newFile);
            }
        }

        if (!(new File(FileUtil.getConfigDir() + "/client.yml").exists())) {
            File newFile = new File(FileUtil.getConfigDir() + "/client.yml");
            File oldFile = new File(pathToOldConfig + "/client.yml");
            if (oldFile.exists()) {
                FileUtils.moveFile(oldFile, newFile);
            }
        }

        if (!(new File(FileUtil.getConfigDir() + "/favorites.yml").exists())) {
            File newFile = new File(FileUtil.getConfigDir() + "/favorites.yml");
            File oldFile = new File(pathToOldConfig + "/favorites.yml");
            if (oldFile.exists()) {
                FileUtils.moveFile(oldFile, newFile);
            }
        }

        if (!(new File(FileUtil.getConfigDir() + "/minimap.yml").exists())) {
            File newFile = new File(FileUtil.getConfigDir() + "/minimap.yml");
            File oldFile = new File(pathToOldConfig + "/minimap.yml");
            if (oldFile.exists()) {
                FileUtils.moveFile(oldFile, newFile);
            }
        }

        if (!(new File(FileUtil.getConfigDir() + "/shortcuts.yml").exists())) {
            File newFile = new File(FileUtil.getConfigDir() + "/shortcuts.yml");
            File oldFile = new File(pathToOldConfig + "/shortcuts.yml");
            if (oldFile.exists()) {
                FileUtils.copyFile(oldFile, newFile);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    relative = new File(pathToOldConfig + "/..");

    try {
        pathToOldConfig = relative.getCanonicalPath();
    } catch (IOException e) {
        pathToOldConfig = relative.getAbsolutePath();
    }

    try {
        if (!(new File(FileUtil.getSpoutcraftBaseDir() + "/options.txt").exists())) {
            File newFile = new File(FileUtil.getSpoutcraftBaseDir() + "/options.txt");
            File oldFile = new File(pathToOldConfig + "/options.txt");
            if (oldFile.exists()) {
                FileUtils.copyFile(oldFile, newFile);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.spoutcraft.client.io.DownloadAssets.java

public static void downloadFile(File destination, String filename, String url, boolean forceOverwrite) {
    File getFile = new File(destination, File.separator + filename);
    // Refresh every day if file exists and not forced overwrite.
    if (!getFile.exists() || forceOverwrite
            || (System.currentTimeMillis() - getFile.lastModified() > (1L * 24 * 60 * 60 * 1000))) {
        try {// w  ww  . j  a v a 2  s  .  com
            URL test = new URL(url);
            HttpURLConnection urlConnect = (HttpURLConnection) test.openConnection();
            System.setProperty("http.agent", "");
            urlConnect.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
            File temp = new File(FileUtil.getConfigDir(), "getFile.temp");
            if (temp.exists()) {
                temp.delete();
            }

            boolean deletedFile = getFile.delete();

            FileUtils.copyInputStreamToFile(urlConnect.getInputStream(), temp);
            FileUtils.moveFile(temp, getFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.structnetalign.util.NetworkUtils.java

public static void writeNetwork(EntrySet entrySet, File file) {

    logger.info("Writing network to " + file);

    PsimiXmlWriter psimiXmlWriter = new PsimiXmlWriter(XML_VERSION);
    try {// w w  w  .j  a  v a2 s . com
        psimiXmlWriter.write(entrySet, file);
    } catch (PsimiXmlWriterException e) {
        throw new RuntimeException("Couldn't write XML to " + file.getPath(), e);
    }

    // to reduce file size
    File tmp = new File(file + ".spaces.xml.tmp");
    try {
        FileUtils.moveFile(file, tmp);
        spacesToTabs(tmp, file, 4);
        tmp.delete();
    } catch (IOException e) {
        logger.warn("Could not convert spaces in " + file.getPath() + " to tabs", e);
    }

    logger.info("Wrote network to " + file);

}

From source file:org.syncany.connection.plugins.ftp.FtpTransferManager.java

@Override
public void download(RemoteFile remoteFile, File localFile) throws StorageException {
    connect();/*  ww w  . j a v  a 2s  .c o  m*/

    String remotePath = getRemoteFile(remoteFile);

    try {
        // Download file
        File tempFile = createTempFile(localFile.getName());
        OutputStream tempFOS = new FileOutputStream(tempFile);

        if (logger.isLoggable(Level.INFO)) {
            logger.log(Level.INFO, "FTP: Downloading {0} to temp file {1}",
                    new Object[] { remotePath, tempFile });
        }

        ftp.retrieveFile(remotePath, tempFOS);

        tempFOS.close();

        // Move file
        if (logger.isLoggable(Level.INFO)) {
            logger.log(Level.INFO, "FTP: Renaming temp file {0} to file {1}",
                    new Object[] { tempFile, localFile });
        }

        localFile.delete();
        FileUtils.moveFile(tempFile, localFile);
        tempFile.delete();
    } catch (IOException ex) {
        forceFtpDisconnect();

        logger.log(Level.SEVERE, "Error while downloading file " + remoteFile.getName(), ex);
        throw new StorageException(ex);
    }
}

From source file:org.syncany.connection.plugins.local.LocalTransferManager.java

@Override
public void download(RemoteFile remoteFile, File localFile) throws StorageException {
    connect();//from   w w w. ja va2  s. co  m

    File repoFile = getRemoteFile(remoteFile);

    if (!repoFile.exists()) {
        throw new StorageException("No such file in local repository: " + repoFile);
    }

    try {
        File tempLocalFile = createTempFile("local-tm-download");
        tempLocalFile.deleteOnExit();

        copyLocalFile(repoFile, tempLocalFile);

        localFile.delete();
        FileUtils.moveFile(tempLocalFile, localFile);
        tempLocalFile.delete();
    } catch (IOException ex) {
        throw new StorageException("Unable to copy file " + repoFile + " from local repository to " + localFile,
                ex);
    }
}