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:dk.netarkivet.harvester.harvesting.IngestableFiles.java

/**
 * Given an archive sub-directory name and a filter to match against this
 * method tries to rename the matched files. Files that can not be renamed
 * generate a log message. The filter should always match files that end
 * with ".open" as a minimum./*from w  ww  . jav a 2s.c om*/
 * @param archiveDirName archive directory name, currently "arc" or "warc"
 * @param filter filename filter used to select ".open" files to rename
 */
protected void closeOpenFiles(String archiveDirName, FilenameFilter filter) {
    File arcsdir = new File(crawlDir, archiveDirName);
    File[] files = arcsdir.listFiles(filter);
    if (files != null) {
        for (File file : files) {
            final String fname = file.getAbsolutePath();
            //Note: Due to regexp we know filename is at least 5 characters
            File tofile = new File(fname.substring(0, fname.length() - 5));
            if (!file.renameTo(tofile)) {
                log.warn("Failed to rename '" + file.getAbsolutePath() + "' to '" + tofile.getAbsolutePath()
                        + "'");
            }
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.web1t.util.Web1TConverter.java

private int processInputFileForLevel(int level, Comparator<String> comparator) throws IOException {

    File unsortedInputFile = new File(outputPath, level + ".txt");

    File outputFolder = getOutputFolder(level);
    outputFolder.mkdir();//from  w  ww . ja  v a2s  .  co  m

    FrequencyDistribution<String> letterFD = letterFDs.get(level);

    Web1TFileSplitter splitter = new Web1TFileSplitter(unsortedInputFile, outputFolder, outputEncoding,
            letterFD, splitThreshold, 0);

    splitter.split();
    LinkedList<File> splitFiles = splitter.getFiles();

    Web1TFileSorter sorter = new Web1TFileSorter(splitFiles, comparator);
    sorter.sort();
    splitter.cleanUp(); // Remove files from previous step

    LinkedList<File> sortedFiles = sorter.getSortedFiles();

    Web1TFileConsolidator consolidator = new Web1TFileConsolidator(sortedFiles, comparator, outputEncoding,
            minFrequency);

    consolidator.consolidate();
    sorter.cleanUp(); // Remove files from previous step

    LinkedList<File> consolidatedFiles = consolidator.getConsolidatedFiles();

    // rename consolidated files -> final index files
    for (File file : consolidatedFiles) {
        String name = Web1TUtil.cutOffUnderscoredSuffixFromFileName(file);
        file.renameTo(new File(name));
    }

    consolidator.cleanUp();

    unsortedInputFile.delete();

    return splitter.getNextUnusedFileNumber();
}

From source file:com.adamrosenfield.wordswithcrosses.versions.DefaultUtil.java

public void downloadFile(URL url, Map<String, String> headers, File destination, boolean notification,
        String title, HttpContext httpContext) throws IOException {
    String scrubbedUrl = AbstractDownloader.scrubUrl(url);
    File tempFile = new File(WordsWithCrossesApplication.TEMP_DIR, destination.getName());
    LOG.info("DefaultUtil: Downloading " + scrubbedUrl + " ==> " + tempFile);
    FileOutputStream fos = new FileOutputStream(tempFile);
    try {//  w  w w .  ja  v  a2s. c  om
        downloadHelper(url, scrubbedUrl, headers, httpContext, fos);
    } finally {
        fos.close();
    }

    if (!tempFile.equals(destination) && !tempFile.renameTo(destination)) {
        throw new IOException("Failed to rename " + tempFile + " to " + destination);
    }

    LOG.info("DefaultUtil: Download succeeded: " + scrubbedUrl);
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.web1t.util.Web1TConverter.java

/**
 * The default file for words which do not account for <code>thresholdSplit</code> percent may
 * have grown large. In order to prevent an real large misc. file we split again.
 *//*from w  w w .jav a 2 s .c  om*/
private void processCreatedMiscFileAgain(int level, Comparator<String> comparator, int nextFileNumber)
        throws IOException {

    File folder = getOutputFolder(level);
    File misc = new File(folder, "99999999");

    if (!misc.exists()) {
        return;
    }

    FrequencyDistribution<String> letterFD = createFreqDistForMiscFile(misc);

    float oldThreshold = splitThreshold;
    // Make sure that the misc file is split into little pieces
    splitThreshold /= 10;

    Web1TFileSplitter splitter = new Web1TFileSplitter(misc, folder, "UTF-8", letterFD, splitThreshold,
            nextFileNumber);
    splitter.split();
    LinkedList<File> splittedFiles = splitter.getFiles();

    Web1TFileSorter sorter = new Web1TFileSorter(splittedFiles, comparator);
    sorter.sort();
    LinkedList<File> sortedFiles = splitter.getFiles();

    splitThreshold = oldThreshold;
    misc.delete();

    Web1TFileConsolidator consolidator = new Web1TFileConsolidator(sortedFiles, comparator, outputEncoding,
            minFrequency);
    consolidator.consolidate();

    LinkedList<File> consolidatedFiles = consolidator.getConsolidatedFiles();

    // rename consolidated files -> final index files
    for (File file : consolidatedFiles) {
        String name = Web1TUtil.cutOffUnderscoredSuffixFromFileName(file);
        file.renameTo(new File(name));
    }

    splitter.cleanUp();
    sorter.cleanUp();
    consolidator.cleanUp();
}

From source file:com.haw3d.jadvalKalemat.versions.DefaultUtil.java

public void downloadFile(URL url, Map<String, String> headers, File destination, boolean notification,
        String title, HttpContext httpContext) throws IOException {
    String scrubbedUrl = AbstractDownloader.scrubUrl(url);
    File tempFile = new File(jadvalKalematApplication.TEMP_DIR, destination.getName());
    LOG.info("DefaultUtil: Downloading " + scrubbedUrl + " ==> " + tempFile);
    FileOutputStream fos = new FileOutputStream(tempFile);
    try {/* w  w  w  .  j  a v  a 2s. co m*/
        downloadHelper(url, scrubbedUrl, headers, httpContext, fos);
    } finally {
        fos.close();
    }

    if (!tempFile.equals(destination) && !tempFile.renameTo(destination)) {
        throw new IOException("Failed to rename " + tempFile + " to " + destination);
    }

    LOG.info("DefaultUtil: Download succeeded: " + scrubbedUrl);
}

From source file:com.cloudbees.hudson.plugins.folder.computed.EventOutputStreams.java

@SuppressWarnings("ResultOfMethodCallIgnored")
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
private void offer(byte[] content) throws IOException {
    int pendingSize;
    if (content == null) {
        pendingSize = this.pendingSize.get();
    } else {/*from w  w w  .j  a  v a2 s .  c o m*/
        if (!pending.offer(content)) {
            throw new IOException("buffer full");
        }
        pendingSize = this.pendingSize.addAndGet(content.length);
    }
    if (content == null || pendingSize >= flushSize
            || System.nanoTime() - lastFlushNanos > flushIntervalNanos) {
        synchronized (writeLock) {
            if (!outputFile.canWriteNow()) {
                return;
            }
            File file = outputFile.get();
            if (!appendNextOpen || file.length() > rotateSize) {
                if (fileCount > 0) {
                    for (int i = fileCount - 1; i >= 0; i--) {
                        File f = i == 0 ? file : new File(file.getParent(), file.getName() + "." + (i));
                        if (f.exists()) {
                            File n = new File(file.getParent(), file.getName() + "." + (i + 1));
                            n.delete();
                            f.renameTo(n);
                        }
                    }
                } else {
                    appendNextOpen = false;
                }
            }
            FileOutputStream os = null;
            try {
                os = new FileOutputStream(file, appendNextOpen);
                byte[] bytes;
                while (null != (bytes = pending.poll())) {
                    this.pendingSize.addAndGet(-bytes.length);
                    os.write(bytes);
                }
                os.flush();
            } catch (IOException e) {
                // ignore
            } finally {
                appendNextOpen = true;
                IOUtils.closeQuietly(os);
            }
        }
    }
}

From source file:org.shept.util.FtpFileCopy.java

/**
 * Compare the source path and the destination path for filenames with the filePattern
 * e.g. *.bak, *tmp and copy these files to the destination dir if they are not present at the
 * destination or if they have changed (by modifactionDate).
 * Copying is done through a retrieve operation.
 * //from ww  w.j  ava  2 s  .  c o  m
 * @param ftpSource
 * @param localDestPat
 * @param filePattern
 * @return the number of files being copied
 * @throws IOException 
 */
public Integer syncPull(FTPClient ftpSource, String localDestPat, String filePattern) throws IOException {
    // check for new files since the last check which need to be copied

    Integer number = 0;
    SortedMap<FileNameDate, File> destMap = FileUtils.fileMapByNameAndDate(localDestPat, filePattern);
    SortedMap<FileNameDate, FTPFile> sourceMap = fileMapByNameAndDate(ftpSource, filePattern);
    // identify the list of source files different from their destinations
    for (FileNameDate fk : destMap.keySet()) {
        sourceMap.remove(fk);
    }

    // copy the list of files from source to destination
    for (FTPFile file : sourceMap.values()) {
        logger.debug("Copying file " + file.getName() + ": " + file.getTimestamp());
        File copy = new File(localDestPat, file.getName());
        try {
            if (!copy.exists()) {
                // copy to tmp file first to avoid clashes during lengthy copy action
                File tmp = File.createTempFile("vrs", ".tmp", copy.getParentFile());
                FileOutputStream writeStream = new FileOutputStream(tmp);
                boolean rc = ftpSource.retrieveFile(file.getName(), writeStream);
                writeStream.close();
                if (rc) {
                    rc = tmp.renameTo(copy);
                    number++;
                }
                if (!rc) {
                    tmp.delete(); // cleanup if we fail
                }
            }
        } catch (IOException ex) {
            logger.error("Ftp FileCopy did not succeed (using " + file.getName() + ")" + " FTP reported error  "
                    + ftpSource.getReplyString(), ex);
        }
    }
    return number;
}

From source file:net.sf.jabref.external.DroppedFileHandler.java

/**
 * Move the given file to the base directory for its file type, and rename
 * it to the given filename.//  w ww .  ja  va  2 s.  c  o  m
 *
 * @param fileName     The name of the source file.
 * @param destFilename The destination filename.
 * @param edits        TODO we should be able to undo this action
 * @return true if the operation succeeded.
 */
private boolean doMove(String fileName, String destFilename, NamedCompound edits) {
    List<String> dirs = panel.getBibDatabaseContext().getFileDirectory();
    int found = -1;
    for (int i = 0; i < dirs.size(); i++) {
        if (new File(dirs.get(i)).exists()) {
            found = i;
            break;
        }
    }
    if (found < 0) {
        // OOps, we don't know which directory to put it in, or the given
        // dir doesn't exist....
        // This should not happen!!
        LOGGER.warn("Cannot determine destination directory or destination directory does not exist");
        return false;
    }
    File toFile = new File(dirs.get(found) + System.getProperty("file.separator") + destFilename);
    if (toFile.exists()) {
        int answer = JOptionPane.showConfirmDialog(frame,
                Localization.lang("'%0' exists. Overwrite file?", toFile.getAbsolutePath()),
                Localization.lang("Overwrite file?"), JOptionPane.YES_NO_OPTION);
        if (answer == JOptionPane.NO_OPTION) {
            return false;
        }
    }

    File fromFile = new File(fileName);
    if (fromFile.renameTo(toFile)) {
        return true;
    } else {
        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not move file '%0'.", toFile.getAbsolutePath())
                        + Localization.lang("Please move the file manually and link in place."),
                Localization.lang("Move file failed"), JOptionPane.ERROR_MESSAGE);
        return false;
    }

}

From source file:org.opensaml.util.http.HttpResource.java

/**
 * Saves the resource data to the backup file. When this method is invoked a temp file is created, the data written
 * to it, and then the existing backup file is deleted and the temp file renamed to the backup file.
 * // www.  j a v a 2s. c  o  m
 * @param data resource data to be written to the backup file
 * 
 * @throws IOException thrown if there is a problem writing the backup file (e.g. if the process does not have write
 *             permission to the backup file)
 */
private void saveToBackupFile(final byte[] data) throws IOException {
    log.debug("Saving backup of response to {}", backupFile.getAbsolutePath());

    final File tmpFile = File.createTempFile(Integer.toString(resourceUrl.hashCode()), null);
    final FileOutputStream out = new FileOutputStream(tmpFile);
    out.write(data);
    out.flush();
    CloseableSupport.closeQuietly(out);
    backupFile.delete();
    tmpFile.renameTo(backupFile);

    log.debug("Wrote {} bytes to backup file {}", backupFile.length(), backupFile.getAbsolutePath());
}

From source file:com.ephesoft.gxt.foldermanager.server.FolderManagerServiceImpl.java

@Override
public Boolean renameFile(String oldName, String newName, String folderPath) {
    File orignalFile = new File(folderPath + File.separator + oldName);
    File renamedFile = new File(folderPath + File.separator + newName);
    if (renamedFile.exists()) {
        return false;
    }/* w ww .j  av  a2  s.  co  m*/
    return orignalFile.renameTo(renamedFile);
}