Example usage for java.io File renameTo

List of usage examples for java.io File renameTo

Introduction

In this page you can find the example usage for java.io File renameTo.

Prototype

public boolean renameTo(File dest) 

Source Link

Document

Renames the file denoted by this abstract pathname.

Usage

From source file:com.sangupta.clitools.dir.FileSort.java

@Override
protected void postProcess() {
    // number of files
    final int num = files.size();

    // now sort these files
    Comparator<File> comparator;
    if ("date".equalsIgnoreCase(this.on)) {
        comparator = new FileDateComparator();
    } else if ("size".equalsIgnoreCase(this.on)) {
        comparator = new FileSizeComparator();
    } else if ("name".equalsIgnoreCase(this.on)) {
        comparator = new FileNameComparator();
    } else {/*from w  w w.j av  a2 s. co m*/
        System.out.println("Unrecognized sort option: " + this.on);
        return;
    }

    // sort
    Collections.sort(this.files, comparator);

    // now depending on the asc/desc order rename
    if (this.descending) {
        Collections.reverse(this.files);
    }

    // iterate
    int count = 1;
    int maxStringSize = String.valueOf(num).length();
    for (File file : this.files) {
        File baseDir = file.getParentFile();
        String newName = format(maxStringSize, count++) + "-" + file.getName();
        System.out.println("Renaming file " + file.getAbsolutePath() + " to " + newName);
        file.renameTo(new File(baseDir, newName));
    }
}

From source file:edu.isi.wings.portal.servlets.HandleUpload.java

/**
 * Handle an HTTP POST request from Plupload.
 *//* w ww .  ja  v a  2  s  . c  o m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    Config config = new Config(request);
    if (!config.checkDomain(request, response))
        return;

    Domain dom = config.getDomain();

    String name = null;
    String id = null;
    String storageDir = dom.getDomainDirectory() + "/";
    int chunk = 0;
    int chunks = 0;
    boolean isComponent = false;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter;
        try {
            iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                try {
                    InputStream input = item.openStream();
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String value = Streams.asString(input);
                        if ("name".equals(fieldName))
                            name = value.replaceAll("[^\\w\\.\\-_]+", "_");
                        else if ("id".equals(fieldName))
                            id = value;
                        else if ("type".equals(fieldName)) {
                            if ("data".equals(value))
                                storageDir += dom.getDataLibrary().getStorageDirectory();
                            else if ("component".equals(value)) {
                                storageDir += dom.getConcreteComponentLibrary().getStorageDirectory();
                                isComponent = true;
                            } else {
                                storageDir = System.getProperty("java.io.tmpdir");
                            }
                        } else if ("chunk".equals(fieldName))
                            chunk = Integer.parseInt(value);
                        else if ("chunks".equals(fieldName))
                            chunks = Integer.parseInt(value);
                    } else if (name != null) {
                        File storageDirFile = new File(storageDir);
                        if (!storageDirFile.exists())
                            storageDirFile.mkdirs();
                        File uploadFile = new File(storageDirFile.getPath() + "/" + name + ".part");
                        saveUploadFile(input, uploadFile, chunk);
                    }
                } catch (Exception e) {
                    this.printError(out, e.getMessage());
                    e.printStackTrace();
                }
            }
        } catch (FileUploadException e1) {
            this.printError(out, e1.getMessage());
            e1.printStackTrace();
        }
    } else {
        this.printError(out, "Not multipart data");
    }

    if (chunks == 0 || chunk == chunks - 1) {
        // Done upload
        File partUpload = new File(storageDir + File.separator + name + ".part");
        File finalUpload = new File(storageDir + File.separator + name);
        partUpload.renameTo(finalUpload);

        String mime = new Tika().detect(finalUpload);
        if (mime.equals("application/x-sh") || mime.startsWith("text/"))
            FileUtils.writeLines(finalUpload, FileUtils.readLines(finalUpload));

        // Check if this is a zip file and unzip if needed
        String location = finalUpload.getAbsolutePath();
        if (isComponent && mime.equals("application/zip")) {
            String dirname = new URI(id).getFragment();
            location = StorageHandler.unzipFile(finalUpload, dirname, storageDir);
            finalUpload.delete();
        }
        this.printOk(out, location);
    }
}

From source file:FileUtils.java

/**
 * Rename the file to temporaty name with given prefix
 * /*from   w  w w. j a  v a 2 s.  c  o m*/
 * @param flFileToRename - file to rename
 * @param strPrefix - prefix to use
 * @throws IOException - error message
 */
public static void renameToTemporaryName(File flFileToRename, String strPrefix) throws IOException {
    assert strPrefix != null : "Prefix cannot be null.";

    String strParent;
    StringBuffer sbBuffer = new StringBuffer();
    File flTemp;
    int iIndex = 0;

    strParent = flFileToRename.getParent();

    // Generate new name for the file in a deterministic way
    do {
        iIndex++;
        sbBuffer.delete(0, sbBuffer.length());
        if (strParent != null) {
            sbBuffer.append(strParent);
            sbBuffer.append(File.separatorChar);
        }

        sbBuffer.append(strPrefix);
        sbBuffer.append("_");
        sbBuffer.append(iIndex);
        sbBuffer.append("_");
        sbBuffer.append(flFileToRename.getName());

        flTemp = new File(sbBuffer.toString());
    } while (flTemp.exists());

    // Now we should have unique name
    if (!flFileToRename.renameTo(flTemp)) {
        throw new IOException(
                "Cannot rename " + flFileToRename.getAbsolutePath() + " to " + flTemp.getAbsolutePath());
    }
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.FileDownloader.java

/**
 * ???/*from  w  w w .  jav  a 2s .c  o m*/
 *
 * @param oldName
 *            :??
 * @param newName
 *            :??
 */
private void renameFile(String oldName, String newName) {
    File file = new File(oldName);
    file.renameTo(new File(newName));
}

From source file:it.openutils.mgnlaws.magnolia.datastore.CachedS3DataRecord.java

public CachedS3DataRecord(S3DataRecord record, File cacheDirectory, File temp)
        throws DataStoreException, IOException {
    super(record.getIdentifier());
    this.length = record.getLength();
    this.lastModified = record.getLastModified();

    fileToStream = File.createTempFile(this.getIdentifier().toString() + "-", null, cacheDirectory);
    temp.renameTo(fileToStream);
    fileToStreamAbsolutePath = fileToStream.getAbsolutePath();
    fileToStream = null;//from  ww  w  .  ja va  2s  .  co  m
}

From source file:com.chiorichan.plugin.loader.Plugin.java

final void init(PluginLoader loader, PluginDescriptionFile description, File dataFolder, File file,
        ClassLoader classLoader) {
    this.loader = loader;
    this.file = file;
    this.description = description;
    this.dataFolder = dataFolder;
    this.classLoader = classLoader;

    File yamlFile = new File(dataFolder, "config.yaml");
    File ymlFile = new File(dataFolder, "config.yml");

    if (ymlFile.exists())
        ymlFile.renameTo(yamlFile);

    this.configFile = yamlFile;
}

From source file:at.jps.sanction.core.io.file.FileInputWorker.java

protected void parseFiles(final File[] files) {
    for (final File file : files) {

        if (file.exists()) {
            logger.info("start parsing file: " + file);
            // TODO: atomic & recoverable !!!!

            final File bsyFile = new File(file.getAbsolutePath() + ".bsy");
            file.renameTo(bsyFile);

            final boolean parsedOK = getFileParser() != null ? getFileParser().parse(bsyFile) : false;

            final File endFile = new File(file.getAbsolutePath() + (parsedOK ? ".end" : ".err"));
            bsyFile.renameTo(endFile);//www .j  a v  a 2  s. c om

            if (parsedOK) {
                logger.info("finished parsing file: " + file + " OK");
            } else {
                logger.error("finished parsing file: " + file + " FAILED");
            }

        } else {
            logger.info("already taken file: " + file);
        }
    }
}

From source file:dk.netarkivet.common.utils.FileUtils.java

/**
 * Attempt to move a file using rename, and if that fails, move the file
 * by copy-and-delete./*from  ww w  . j av a 2s  . com*/
 * @param fromFile The source
 * @param toFile The target
 */
public static void moveFile(File fromFile, File toFile) {
    ArgumentNotValid.checkNotNull(fromFile, "File fromFile");
    ArgumentNotValid.checkNotNull(toFile, "File toFile");

    if (!fromFile.renameTo(toFile)) {
        copyFile(fromFile, toFile);
        remove(fromFile);
    }
}

From source file:fr.gael.dhus.server.http.SolrWebapp.java

@Override
public void afterPropertiesSet() throws Exception {
    try {// w  ww  .  ja  v a  2  s  .  c om
        SolrConfiguration solr = configurationManager.getSolrConfiguration();

        File solrroot = new File(solr.getPath());
        System.setProperty("solr.solr.home", solrroot.getAbsolutePath());

        File libdir = new File(solrroot, "lib");
        libdir.mkdirs();
        File coredir = new File(solrroot, "dhus");
        coredir.mkdirs();
        File confdir = new File(coredir, "conf");

        // Move old data/conf dirs if any
        File olddata = new File(solrroot, "data/dhus");
        if (olddata.exists()) {
            File newdata = new File(coredir, "data");
            olddata.renameTo(newdata);
        }
        File oldconf = new File(solrroot, "conf");
        if (oldconf.exists()) {
            oldconf.renameTo(confdir);
        }
        confdir.mkdirs();
        // Rename old `schema.xml` file to `managed-schema`
        File schemafile = new File(confdir, "managed-schema");
        File oldschema = new File(confdir, "schema.xml");
        if (oldschema.exists()) {
            oldschema.renameTo(schemafile);
        }

        // solr.xml
        InputStream input = ClassLoader.getSystemResourceAsStream("fr/gael/dhus/server/http/solr/solr.xml");
        OutputStream output = new FileOutputStream(new File(solrroot, "solr.xml"));
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/core.properties
        input = ClassLoader.getSystemResourceAsStream("fr/gael/dhus/server/http/solr/core.properties");
        File core_props = new File(coredir, "core.properties");
        output = new FileOutputStream(core_props);
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/solrconfig.xml
        input = ClassLoader.getSystemResourceAsStream("fr/gael/dhus/server/http/solr/solrconfig.xml");
        File solrconfigfile = new File(confdir, "solrconfig.xml");
        output = new FileOutputStream(solrconfigfile);
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/schema.xml
        if (!schemafile.exists()) {
            String schemapath = solr.getSchemaPath();
            if ((schemapath == null) || ("".equals(schemapath)) || (!(new File(schemapath)).exists())) {
                input = ClassLoader.getSystemResourceAsStream("fr/gael/dhus/server/http/solr/schema.xml");
            } else {
                input = new FileInputStream(new File(schemapath));
            }
            output = new FileOutputStream(schemafile);
            IOUtils.copy(input, output);
            output.close();
            input.close();
        }

        // dhus/stopwords.txt
        input = ClassLoader.getSystemResourceAsStream("fr/gael/dhus/server/http/solr/stopwords.txt");
        output = new FileOutputStream(new File(confdir, "stopwords.txt"));
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/synonyms.txt
        String synonympath = solr.getSynonymPath();
        if ((synonympath == null) || ("".equals(synonympath)) || (!(new File(synonympath)).exists())) {
            input = ClassLoader.getSystemResourceAsStream("fr/gael/dhus/server/http/solr/synonyms.txt");
        } else {
            input = new FileInputStream(new File(synonympath));
        }
        output = new FileOutputStream(new File(confdir, "synonyms.txt"));
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/xslt/opensearch_atom.xsl
        input = ClassLoader.getSystemResourceAsStream("fr/gael/dhus/server/http/solr/xslt/opensearch_atom.xsl");
        if (input != null) {
            File xslt_dir = new File(confdir, "xslt");
            if (!xslt_dir.exists()) {
                xslt_dir.mkdirs();
            }
            output = new FileOutputStream(new File(xslt_dir, "opensearch_atom.xsl"));
            IOUtils.copy(input, output);
            output.close();
            input.close();
        } else {
            LOGGER.warn("Cannot file opensearch xslt file. " + "Opensearch interface is not available.");
        }

        solrInitializer.createSchema(coredir.getAbsolutePath(), schemafile.getAbsolutePath());

    } catch (IOException e) {
        throw new UnsupportedOperationException("Cannot initialize Solr service.", e);
    }
}

From source file:net.ftb.minecraft.MCInstaller.java

/**
 * Gather assets to check/download. If force update is enabled this will return all assets
 *
 * @return null if failed and MC can't be started, otherwise, ArrayList containing assets to be checked/downloaded
 *              Normally, if offline mode works, setupNewStyle() and gatherAssets() are not called and error situation is impossible
 *              Returning null just in case of network breakge after authentication process
 *///from  w w w .j  av a 2  s.  c  o m
private static List<DownloadInfo> gatherAssets(final File root, String mcVersion, String installDir) {
    try {
        Logger.logInfo("Checking local assets file, for MC version" + mcVersion + " Please wait! ");
        List<DownloadInfo> list = Lists.newArrayList();
        Boolean forceUpdate = Settings.getSettings().isForceUpdateEnabled();

        /*
         * vanilla minecraft.jar
         */

        File local = new File(root, "versions/{MC_VER}/{MC_VER}.jar".replace("{MC_VER}", mcVersion));
        if (!local.exists() || forceUpdate) {
            list.add(new DownloadInfo(
                    new URL(Locations.mc_dl + "versions/{MC_VER}/{MC_VER}.jar".replace("{MC_VER}", mcVersion)),
                    local, local.getName()));
        }

        /*
         * <ftb installation location>/libraries/*
         */
        //check if our copy exists of the version json if not backup to mojang's copy
        Logger.logDebug("Checking minecraft.jar");
        URL url = new URL(DownloadUtils.getStaticCreeperhostLinkOrBackup(
                "mcjsons/versions/{MC_VER}/{MC_VER}.json".replace("{MC_VER}", mcVersion),
                Locations.mc_dl + "versions/{MC_VER}/{MC_VER}.json".replace("{MC_VER}", mcVersion)));
        File json = new File(root, "versions/{MC_VER}/{MC_VER}.json".replace("{MC_VER}", mcVersion));

        DownloadUtils.downloadToFile(url, json, 3);
        if (!json.exists()) {
            Logger.logError("library JSON not found");
            return null;
        }

        Version version = JsonFactory.loadVersion(json);
        //TODO make sure to  setup lib DL's for pack.json!!!
        Logger.logDebug("checking minecraft libraries");
        for (Library lib : version.getLibraries()) {
            if (lib.natives == null) {
                local = new File(root, "libraries/" + lib.getPath());
                if (!local.exists() || forceUpdate) {
                    if (!lib.getUrl().toLowerCase().equalsIgnoreCase(Locations.ftb_maven)) {//DL's shouldn't be coming from maven repos but ours or mojang's
                        list.add(new DownloadInfo(new URL(lib.getUrl() + lib.getPath()), local, lib.getPath()));
                    } else {
                        list.add(new DownloadInfo(
                                new URL(DownloadUtils.getCreeperhostLink(lib.getUrl() + lib.getPath())), local,
                                lib.getPath(), true));
                    }
                }
            } else {
                local = new File(root, "libraries/" + lib.getPathNatives());
                if (!local.exists() || forceUpdate) {
                    list.add(new DownloadInfo(new URL(lib.getUrl() + lib.getPathNatives()), local,
                            lib.getPathNatives()));
                }

            }
        }

        //Pack JSON Libraries
        Logger.logDebug("Checking pack libararies");
        ModPack pack = ModPack.getSelectedPack();
        File packDir = new File(installDir, pack.getDir());
        File gameDir = new File(packDir, "minecraft");
        File libDir = new File(installDir, "libraries");
        if (!pack.getDir().equals("mojang_vanilla")) {
            if (new File(gameDir, "pack.json").exists()) {
                Version packjson = JsonFactory.loadVersion(new File(gameDir, "pack.json"));
                for (Library lib : packjson.getLibraries()) {
                    //Logger.logError(new File(libDir, lib.getPath()).getAbsolutePath());
                    // These files are shipped inside pack.zip, can't do force update check yet
                    local = new File(root, "libraries/" + lib.getPath());
                    if (!new File(libDir, lib.getPath()).exists()) {
                        if (lib.checksums != null)
                            list.add(new DownloadInfo(new URL(lib.getUrl() + lib.getPath()), local,
                                    lib.getPath(), lib.checksums, "sha1", DownloadInfo.DLType.NONE,
                                    DownloadInfo.DLType.NONE));
                        else if (lib.download != null && lib.download)
                            list.add(new DownloadInfo(new URL(lib.getUrl() + lib.getPath()), local,
                                    lib.getPath()));
                    }
                }
            }
        } else {
            //TODO handle vanilla packs w/ tweakers w/ this stuffs !!!
        }

        // Move the old format to the new:
        File test = new File(root, "assets/READ_ME_I_AM_VERY_IMPORTANT.txt");
        if (test.exists()) {
            Logger.logDebug("Moving old format");
            File assets = new File(root, "assets");
            Set<File> old = FileUtils.listFiles(assets);
            File objects = new File(assets, "objects");
            String[] skip = new String[] { objects.getAbsolutePath(),
                    new File(assets, "indexes").getAbsolutePath(),
                    new File(assets, "virtual").getAbsolutePath() };

            for (File f : old) {
                String path = f.getAbsolutePath();
                boolean move = true;
                for (String prefix : skip) {
                    if (path.startsWith(prefix))
                        move = false;
                }
                if (move) {
                    String hash = DownloadUtils.fileSHA(f);
                    File cache = new File(objects, hash.substring(0, 2) + "/" + hash);
                    Logger.logInfo("Caching Asset: " + hash + " - "
                            + f.getAbsolutePath().replace(assets.getAbsolutePath(), ""));
                    if (!cache.exists()) {
                        cache.getParentFile().mkdirs();
                        f.renameTo(cache);
                    }
                    f.delete();
                }
            }

            List<File> dirs = FileUtils.listDirs(assets);
            for (File dir : dirs) {
                if (dir.listFiles().length == 0) {
                    dir.delete();
                }
            }
        }

        /*
         * assets/*
         */
        Logger.logDebug("Checking minecraft assets");
        url = new URL(Locations.mc_dl + "indexes/{INDEX}.json".replace("{INDEX}", version.getAssets()));
        json = new File(root, "assets/indexes/{INDEX}.json".replace("{INDEX}", version.getAssets()));

        DownloadUtils.downloadToFile(url, json, 3);
        if (!json.exists()) {
            Logger.logError("asset JSON not found");
            return null;
        }

        AssetIndex index = JsonFactory.loadAssetIndex(json);

        Benchmark.start("threading");
        long size = list.size();
        Collection<DownloadInfo> tmp;
        Logger.logDebug("Starting TaskHandler to check MC assets");
        Parallel.TaskHandler th = new Parallel.ForEach(index.objects.entrySet())
                .withFixedThreads(2 * OSUtils.getNumCores())
                //.configurePoolSize(2*2*OSUtils.getNumCores(), 10)
                .apply(new Parallel.F<Map.Entry<String, AssetIndex.Asset>, DownloadInfo>() {
                    public DownloadInfo apply(Map.Entry<String, AssetIndex.Asset> e) {
                        try {
                            //Logger.logDebug("YYYY" + System.currentTimeMillis());
                            String name = e.getKey();
                            AssetIndex.Asset asset = e.getValue();
                            String path = asset.hash.substring(0, 2) + "/" + asset.hash;
                            final File local = new File(root, "assets/objects/" + path);
                            if (local.exists() && !asset.hash.equals(DownloadUtils.fileSHA(local))) {
                                local.delete();
                            }
                            if (!local.exists()) {
                                return (new DownloadInfo(new URL(Locations.mc_res + path), local, name,
                                        Lists.newArrayList(asset.hash), "sha1"));
                            }
                        } catch (Exception ex) {
                            Logger.logError("Asset hash check failed", ex);
                        }
                        // values() will drop null entries
                        return null;
                    }
                });
        tmp = th.values();
        list.addAll(tmp);
        // kill executorservice
        th.shutdown();
        Benchmark.logBenchAs("threading", "parallel asset check");

        return list;
    } catch (Exception e) {
        Logger.logError("Error while gathering assets", e);
    }
    return null;
}