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:net.sourceforge.atunes.kernel.executors.processes.ExportFilesProcess.java

public void run() {
    File destination = new File(path);
    int filesExported = 0;

    HandlerProxy.getVisualHandler().getExportProgressDialog().getProgressLabel()
            .setText(Integer.toString(filesExported));
    boolean errors = false;
    logger.info("Exporting songs to " + destination);
    try {/*from  w w  w. j a v  a2  s  .c om*/
        for (Iterator it = songs.iterator(); it.hasNext() && !interrupt;) {
            AudioFile song = (AudioFile) it.next();
            File destDir = getDirectory(song, destination, structure);
            FileUtils.copyFileToDirectory(song, destDir);
            if (filePattern != null) {
                File destFile = new File(
                        destDir.getAbsolutePath() + SystemProperties.fileSeparator + song.getName());
                String newName = getNewName(filePattern, song);
                destFile.renameTo(
                        new File(destDir.getAbsolutePath() + SystemProperties.fileSeparator + newName));
            }
            filesExported++;
            HandlerProxy.getVisualHandler().getExportProgressDialog().getProgressLabel()
                    .setText(Integer.toString(filesExported));
            HandlerProxy.getVisualHandler().getExportProgressDialog().getProgressBar().setValue(filesExported);
        }
    } catch (IOException e) {
        errors = true;
        logger.error(e.getMessage());
    }
    logger.info("Exporting process done");
    CopyProgressDialog dialog = HandlerProxy.getVisualHandler().getExportProgressDialog();
    dialog.setVisible(false);
    if (errors)
        HandlerProxy.getVisualHandler().showErrorDialog(LanguageTool.getString("ERRORS_IN_EXPORT_PROCESS"));
}

From source file:net.sourceforge.atunes.kernel.executors.ImportProcess.java

public void run() {
    super.run();// ww w .  ja v a  2s. c om
    File destination = new File(HandlerProxy.getRepositoryHandler().getRepositoryPath());
    int filesImported = 0;

    HandlerProxy.getVisualHandler().getCopyProgressDialog().getProgressLabel()
            .setText(Integer.toString(filesImported));
    boolean errors = false;
    logger.info("Copying songs from device to repository");
    try {
        for (Iterator it = songs.iterator(); it.hasNext() && !interrupt;) {
            AudioFile song = (AudioFile) it.next();
            File destDir = getDirectory(song, destination, structure);
            FileUtils.copyFileToDirectory(song, destDir);
            if (filePattern != null) {
                File destFile = new File(
                        destDir.getAbsolutePath() + SystemProperties.fileSeparator + song.getName());
                String newName = getNewName(filePattern, song);
                destFile.renameTo(
                        new File(destDir.getAbsolutePath() + SystemProperties.fileSeparator + newName));
            }
            filesImported++;
            HandlerProxy.getVisualHandler().getCopyProgressDialog().getProgressLabel()
                    .setText(Integer.toString(filesImported));
            HandlerProxy.getVisualHandler().getCopyProgressDialog().getProgressBar().setValue(filesImported);
        }
    } catch (IOException e) {
        errors = true;
        logger.error(e.getMessage());
        logger.debug(e);
    }
    logger.info("Copying process done");
    CopyProgressDialog dialog = HandlerProxy.getVisualHandler().getCopyProgressDialog();
    dialog.setVisible(false);
    if (errors)
        HandlerProxy.getVisualHandler().showErrorDialog(LanguageTool.getString("ERRORS_IN_COPYING_PROCESS"));

}

From source file:com.collaide.fileuploader.requests.repository.RepositoryRequest.java

/**
 * download a file or a folder from the server to the disk a folder is
 * downloaded as a zip and the unzipped<br/>
 *
 * @param url the URL of the repo item to download
 * @param folderToSave the folderin which to save the downloaded item
 * @return The path of the saved file or folder
 * @throws IOException/* www .j a v a  2 s  . com*/
 */
public String download(String url, String folderToSave) throws IOException {
    ClientResponse response = Client.create().resource(url + "?" + CurrentUser.getAuthParams())
            .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    if (response.getStatus() != 200) {
        return null;
    }
    File downloadedFile = response.getEntity(File.class);

    File fileToSave = new File(folderToSave, getFileName(response));
    downloadedFile.renameTo(fileToSave);
    FileWriter fr = new FileWriter(downloadedFile);
    fr.flush();
    String itemName = fileToSave.getAbsolutePath();
    if (isAZip(response)) {
        unzip(fileToSave, new File(folderToSave));
        fileToSave.delete();
        itemName = FilenameUtils.removeExtension(itemName);
    }
    downloadedFile.getAbsolutePath();
    return itemName;
}

From source file:beans.service.LibraryFileUpload.java

public String run(Map<String, String> fields, List<String> fileNames) {

    String first_name = fields.get("first_level_service_name_of_new_library");
    String second_name = fields.get("second_level_service_name_of_new_library");
    if (first_name == null || first_name.length() < 1 || second_name == null || second_name.length() < 1) {
        return ("{\"status\":100, \"message\":\"service name should NOT be empty.\"}");

    }//from w w w.j  av  a  2  s  .  c o m
    if (fileNames.size() != 1) {
        return ("{\"status\":100, \"message\":\"file field missing.\"}");

    }
    File oldFile = new File(fileNames.get(0));
    String baseName = oldFile.getName();
    String destName = LibraryFile.getLibraryFileName(first_name, second_name, baseName);
    File newFile = new File(destName);
    if (!oldFile.renameTo(newFile)) {
        return ("{\"status\":100, \"message\":\"rename file failed.\"}");

    }
    //
    String memo = fields.get("new_library_memo");
    if (memo == null) {
        memo = "";
    }
    String result = insertTable(first_name, second_name, baseName, memo);
    if (result.equals("success")) {
        return String.format("{\"status\":0, \"message\":\"success\", \"file_name\":\"%s\"}", baseName);
    } else {
        return String.format("{\"status\":100, \"message\":\"%s\"}", result);
    }

}

From source file:com.imos.sample.pi.PythonTemperatureSensor.java

public void pythonTemperatureSensor() {

    try {//from ww w.j  ava 2 s  . c om
        String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 22 4";
        int count = 0;
        JSONArray array = new JSONArray();
        int dayOfMonth = 0;
        cal.setTime(new Date());
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        while (true) {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
            String result = output.toString(), tempStr;
            double temp, humid;
            if (result != null && !result.trim().isEmpty()) {
                tempStr = result.substring(result.indexOf("Humid"));
                result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1);
                temp = Double.parseDouble(result);
                result = tempStr;
                result = result.substring(result.indexOf("=") + 1, result.indexOf("%"));
                humid = Double.parseDouble(result);

                JSONObject data = new JSONObject();
                data.put("temp", temp);
                data.put("humid", humid);
                data.put("time", new Date().getTime());

                array.put(data);
            }

            Thread.sleep(60000);
            count++;
            if (count == 60) {
                cal.setTime(new Date());
                StringBuilder builder = new StringBuilder();
                builder.append(cal.get(Calendar.DAY_OF_MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.YEAR));
                builder.append("-");
                builder.append(cal.get(Calendar.HOUR_OF_DAY));
                builder.append("_");
                builder.append(cal.get(Calendar.MINUTE));
                String name = builder.toString();
                Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, "{0} recorded", name);
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(name + "_data.json"))) {
                    writer.append(array.toString());
                } catch (IOException ex) {

                }
                System.out.println(builder.toString());
                count = 0;
                array = new JSONArray();
                if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) {
                    builder = new StringBuilder();
                    builder.append(cal.get(Calendar.DAY_OF_MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.YEAR));
                    String dirName = builder.toString();
                    File newDir = new File("./" + dirName);
                    newDir.mkdir();

                    File files = new File("./");
                    for (File file : files.listFiles()) {
                        if (file.getName().endsWith(".json")) {
                            file.renameTo(new File("./" + dirName + File.separator + file.getName()));
                        }
                    }

                    dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(PythonTemperatureSensor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.izforge.izpack.installer.multiunpacker.MultiVolumeFileUnpackerTest.java

/**
 * Verifies that the {@link VolumeLocator#getVolume(String, boolean)} method is invoked to prompt
 * for missing media./*w  w  w .  jav  a 2 s. c  o  m*/
 *
 * @throws IOException        for any I/O error
 * @throws InstallerException for any installer error
 */
@Test
public void testPromptForNextMedia() throws IOException, InstallerException {
    File baseDir = temporaryFolder.getRoot();
    File source = createSourceFile(baseDir);
    File target = getTargetFile(baseDir);

    // rename the first volume so that it is prompted for
    final File volume1 = new File(volume.getPath() + ".1");
    assertTrue(volume1.exists());
    final File renamed = new File(volume1.getPath() + ".bak");
    assertTrue(volume1.renameTo(renamed));

    VolumeLocator locator = new VolumeLocator() {
        @Override
        public File getVolume(String path, boolean corrupt) throws IOException {
            // rename the file back
            assertTrue(renamed.renameTo(volume1));
            return volume1;
        }
    };

    FileSpanningInputStream stream = new FileSpanningInputStream(volume, volumeCount);
    stream.setLocator(locator);

    FileQueue queue = new FileQueueFactory(Platforms.WINDOWS, getLibrarian()).create();
    FileUnpacker unpacker = new MultiVolumeFileUnpacker(stream, getCancellable(), queue);

    PackFile file = createPackFile(baseDir, source, target, Blockable.BLOCKABLE_NONE);
    assertFalse(target.exists());

    InputStream packStream = createPackStream(source);
    unpacker.unpack(file, packStream, target);
    assertTrue(queue.isEmpty()); // file should not have been queued

    // verify the file unpacked successfully
    checkTarget(source, target);
}

From source file:forge.gui.ImportDialog.java

private static void _copyFile(final File srcFile, final File destFile, final boolean deleteSrcAfter)
        throws IOException {
    destFile.getParentFile().mkdirs();//w  w  w . jav a2 s . com

    // if this is a move, try a simple rename first
    if (deleteSrcAfter) {
        if (srcFile.renameTo(destFile)) {
            return;
        }
    }

    if (!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel src = null;
    FileChannel dest = null;
    try {
        src = new FileInputStream(srcFile).getChannel();
        dest = new FileOutputStream(destFile).getChannel();
        dest.transferFrom(src, 0, src.size());
    } finally {
        if (src != null) {
            src.close();
        }
        if (dest != null) {
            dest.close();
        }
    }

    if (deleteSrcAfter) {
        srcFile.delete();
    }
}

From source file:com.taobao.tanggong.handler.FileLoader.java

protected void save(List<String> lines) {
    if (null != lines && null != this.dataDirectory) {
        File masterFile = new File(this.dataDirectory, this.getFilename());

        File backupFile = new File(this.dataDirectory, this.getFilename() + ".bak");

        if (masterFile.exists()) {
            masterFile.renameTo(backupFile);
        }/*from   ww w  .  j a  va 2 s  .  com*/

        OutputStream output = null;
        try {
            output = new FileOutputStream(masterFile);

            StringBuilder sb = new StringBuilder();
            for (String k : lines) {

                sb.append(k);
                sb.append("\n");
            }

            IOUtils.write(sb.toString(), output);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(output);
        }
    }
}

From source file:edu.stanford.epad.epadws.EPadWebServerVersion.java

public void downloadEpadLatestVersion(String username) throws Exception {
    String jarname = EPADConfig.getParamValue("EPADJarName", "epad-ws-1.1-jar-with-dependencies.jar");
    String warname = EPADConfig.getParamValue("EPADWarName", "ePad.war");
    String base = EPADConfig.getEPADWebServerBaseDir();
    File war = new File(base + "webapps", warname);
    File jar = new File(base + "lib", jarname);

    log.info("Renaming ePAD war...");
    war.renameTo(new File(base + "webapps", warname + "_" + version));
    log.info("Renaming ePAD jar...");
    jar.renameTo(new File(base + "lib", jarname + "_" + version));
    FTPUtil ftp = new FTPUtil("epad-distribution.stanford.edu", null, null);
    try {//  w  w w . j a v  a  2 s  .co m
        log.info("Downloading ePAD war...");
        ftp.getFile(warname, war);
    } catch (Exception x) {
        new File(base + "webapps", warname + "_" + version).renameTo(war);
        new File(base + "lib", jarname + "_" + version).renameTo(jar);
        throw x;
    }
    try {
        log.info("Downloading ePAD jar...");
        ftp.getFile(jarname, jar);
    } catch (Exception x) {
        war.delete();
        new File(base + "webapps", warname + "_" + version).renameTo(war);
        new File(base + "lib", jarname + "_" + version).renameTo(jar);
        log.warning("Error downloading ePAD software", x);
        throw new Exception("Error downloading ePAD software:" + x.getMessage());
    }
    restartRequired = true;
    DefaultEpadProjectOperations.getInstance().createEventLog(username, null, null, null, null, null, null,
            null, "Software Updated", "EPAD System Software has been updated", true);
    EpadDatabase.getInstance().getEPADDatabaseOperations().insertEpadEvent(username,
            "Software updated, Please restart ePAD", "", "", "", "", "", "", "Please restart ePAD");
}

From source file:com.mindquarry.desktop.workspace.conflict.ContentConflict.java

/**
 * Rename a file created in a conflict to make their name them useful for
 * users and vice versa, e.g. 'file.txt.r11' <=> 'file.r11.txt'. Essentially
 * swaps the last two extensions of the filename.
 * /*from www .j a va  2s  .  c o  m*/
 * @param conflictedFilename
 *            Filename of the conflict file (e.g. file.txt.r11).
 * @return the new file
 */
protected static File renameConflictFile(File conflictedFile) {
    if (conflictedFile == null) {
        log.warn("renameConflictFile: conflictedFile is null");
        return null;
    }

    File parentDir = conflictedFile.getParentFile();
    String conflictedFilename = conflictedFile.getName();
    int ext2pos = conflictedFilename.lastIndexOf('.');
    int ext1pos = conflictedFilename.lastIndexOf('.', ext2pos - 1);

    // test if there are less than two extension, and if so skip renaming
    if (ext1pos < 0 || ext2pos < 0) {
        log.info("Skip renaming file '" + conflictedFilename + "'");
        return conflictedFile;
    }

    String name = conflictedFilename.substring(0, ext1pos);
    String ext1 = conflictedFilename.substring(ext1pos + 1, ext2pos);
    String ext2 = conflictedFilename.substring(ext2pos + 1);

    String newFilename = name + "." + ext2 + "." + ext1;
    File newFile = new File(parentDir, newFilename);

    log.info("Renaming '" + conflictedFilename + "' => '" + newFilename + "'");
    conflictedFile.renameTo(newFile);
    return newFile;
}