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:io.github.jeddict.jcode.parser.ejs.EJSUtil.java

public static void insertNeedle(FileObject root, String source, String needlePointer, String needleContent,
        ProgressHandler handler) {//  w  w  w . j  av a2  s .c om
    if (StringUtils.isEmpty(needleContent)) {
        return;
    }
    Charset charset = Charset.forName("UTF-8");
    BufferedReader reader;
    BufferedWriter writer;
    if (source.endsWith("json")) {
        needlePointer = "\"" + needlePointer + "\"";
    } else {
        needlePointer = " " + needlePointer + " ";
    }
    try {
        // temp file
        File outFile = File.createTempFile("needle", "tmp");
        // input
        FileObject sourceFileObject = root.getFileObject(source);
        if (sourceFileObject == null) {
            handler.error("Needle file", String.format("needle file '%s' not found ", source));
            return;
        }
        File sourceFile = FileUtil.toFile(sourceFileObject);
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile), charset));
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), charset));
        StringBuilder content = new StringBuilder();
        boolean contentUpdated = false;
        String thisLine;
        while ((thisLine = reader.readLine()) != null) {
            if (thisLine.contains(needlePointer)) {
                content.append(needleContent);
                contentUpdated = true;
            }
            content.append(thisLine).append("\n");
        }

        IOUtils.write(content.toString(), writer);

        try {
            reader.close();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        try {
            writer.flush();
            writer.close();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        if (contentUpdated) {
            sourceFile.delete();
            outFile.renameTo(sourceFile);
        } else {
            outFile.delete();
        }
    } catch (FileNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:com.safi.workshop.sqlexplorer.sqlpanel.AbstractSQLExecution.java

/**
 * Logs the query to the debug log file, but only if the preferences require it. If the
 * query failed, the exception should be included too.
 * /* w ww  .j a  v  a2 s.co m*/
 * @param query
 * @param e
 */
protected void debugLogQuery(Query query, SQLException sqlException) {
    // Get the logging level
    String level = SQLExplorerPlugin.getDefault().getPreferenceStore()
            .getString(IConstants.QUERY_DEBUG_LOG_LEVEL);
    if (level == null || level.equals(IConstants.QUERY_DEBUG_OFF))
        return;
    if (sqlException == null && level.equals(IConstants.QUERY_DEBUG_FAILED))
        return;

    // Get the log files; if the current log is too big, retire it
    File dir = SQLExplorerPlugin.getDefault().getStateLocation().toFile();
    File log = new File(dir.getAbsolutePath() + '/' + "query-debug.log");
    File oldLog = new File(dir.getAbsolutePath() + '/' + "query-debug.old.log");

    // Too big? Then delete the old and archive the current
    if (log.exists() && log.length() > MAX_DEBUG_LOG_SIZE) {
        oldLog.delete();
        log.renameTo(oldLog);
    }

    // Copy it to the output
    PrintWriter writer = null;
    try {
        FileWriter fw = new FileWriter(log, true);
        writer = new PrintWriter(fw);
        try {
            writer.write("==============================================\r\n");
            StringBuffer sb = new StringBuffer(query.toString());
            for (int i = 0; i < sb.length(); i++)
                if (sb.charAt(i) == '\n')
                    sb.insert(i++, '\r');
            sb.append("\r\n");
            writer.write(sb.toString());
            if (sqlException != null)
                writer.write("FAILED: " + sqlException.getMessage() + "\r\n");
        } finally {
            writer.flush();
            writer.close();
        }
    } catch (IOException e) {
        SQLExplorerPlugin.error("Failed to log query", e);
    }
}

From source file:it.polito.ai.polibox.client.http.action.AbstractFileAction.java

public void renameFs(Resource old, Resource nuova) {
    File oldF, newF;
    String s, w;//  ww  w .  ja  va 2  s.  c  om
    s = old.getName();
    w = nuova.getName();
    try {
        if (!s.startsWith(getTargetFolderCanonicalPath()))
            s = getTargetFolderCanonicalPath() + old.getName();
        if (!w.startsWith(getTargetFolderCanonicalPath()))
            w = getTargetFolderCanonicalPath() + nuova.getName();

        oldF = new File(s);
        newF = new File(w);
        oldF.renameTo(newF);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.sourceforge.atunes.kernel.modules.repository.FileManager.java

@Override
public boolean rename(final ILocalAudioObject audioFile, final String name) {
    File file = getAudioObjectFile(audioFile);
    String extension = FilenameUtils.getExtension(getPath(audioFile));
    String validName = FileNameUtils.getValidFileName(name, this.osManager);
    File newFile = this.osManager.getFile(getFolderPath(audioFile),
            StringUtils.getString(validName, ".", extension));
    // Get associated files before renaming
    List<File> associatedFiles = getAssociatedFiles(audioFile);
    boolean succeeded = file.renameTo(newFile);
    if (succeeded) {
        if (audioFile instanceof AudioFile) {
            ((AudioFile) audioFile).setFile(FileUtils.getNormalizedPath(newFile));
        } else {//from   ww  w. j ava  2  s . co  m
            throw new IllegalArgumentException(StringUtils.getString("setFile operation not implemented for ",
                    audioFile.getClass().getName()));
        }
        // Rename associated files
        for (File associatedFile : associatedFiles) {
            String associatedExtension = FilenameUtils.getExtension(associatedFile.getAbsolutePath());
            File newAssociatedFile = this.osManager.getFile(getFolderPath(audioFile),
                    StringUtils.getString(validName, ".", associatedExtension));
            associatedFile.renameTo(newAssociatedFile);
        }
    }
    return succeeded;
}

From source file:de.bley.word.filewriter.WriterFile.java

/**
 * loescht eine Zeile einer Textdatei.//from  w  ww  .  ja  v  a 2s .c om
 *
 * @param filepath Pfad der Datei.
 * @param text String, welcher aus der Datei geloescht werden soll.
 * @param row Zeile, welche geloescht werden soll.
 *
 */
@Override
public void removeValue(String filepath, final String text, final int row) {
    filepath = "/" + filepath;

    File inFile = new File(filepath);
    File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
    BufferedReader br;
    int counter = 0;

    try {
        br = new BufferedReader(new FileReader(filepath));
        PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

        String line = null;

        //nur eine zeile loeschen
        while ((line = br.readLine()) != null) {

            if (!line.trim().equals(text)) {

                pw.println(line);
                pw.flush();
            }
            counter++;
        }
        pw.close();
        br.close();

        inFile.delete();

        tempFile.renameTo(inFile);

    } catch (Exception ex) {
        log.debug("fehler beim loeschen", ex);
    }
}

From source file:com.bonsai.btcreceive.HDReceiver.java

public void persist() {
    String path = persistPath(mFilePrefix);
    String tmpPath = path + ".tmp";
    try {//w w w  .j  a v  a  2 s .  c  o  m
        // Serialize into a byte array.
        JSONObject jsonobj = dumps();
        String jsonstr = jsonobj.toString(4); // indentation
        byte[] plainBytes = jsonstr.getBytes(Charset.forName("UTF-8"));

        // Ready a tmp file.
        File tmpFile = new File(mDirectory, tmpPath);
        if (tmpFile.exists())
            tmpFile.delete();

        FileOutputStream ostrm = new FileOutputStream(tmpFile);
        ostrm.write(plainBytes);
        ostrm.close();

        // Swap the tmp file into place.
        File newFile = new File(mDirectory, path);
        if (!tmpFile.renameTo(newFile))
            mLogger.warn("failed to rename to " + newFile);
        else
            mLogger.info("persisted to " + path);

    } catch (JSONException ex) {
        mLogger.warn("failed generating JSON: " + ex.toString());
    } catch (IOException ex) {
        mLogger.warn("failed to write to " + tmpPath + ": " + ex.toString());
    } catch (DataLengthException ex) {
        mLogger.warn("encryption failed: " + ex.toString());
    } catch (IllegalStateException ex) {
        mLogger.warn("encryption failed: " + ex.toString());
    }
}

From source file:JarUtil.java

/**
 * Adds the given file to the specified JAR file.
 * /*w  ww.j  a  v a  2 s .c  o  m*/
 * @param file
 *            the file that should be added
 * @param jarFile
 *            The JAR to which the file should be added
 * @param parentDir
 *            the parent directory of the file, this is used to calculate
 *            the path witin the JAR file. When null is given, the file will
 *            be added into the root of the JAR.
 * @param compress
 *            True when the jar file should be compressed
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void addToJar(File file, File jarFile, File parentDir, boolean compress)
        throws FileNotFoundException, IOException {
    File tmpJarFile = File.createTempFile("tmp", ".jar", jarFile.getParentFile());
    JarOutputStream out = new JarOutputStream(new FileOutputStream(tmpJarFile));
    if (compress) {
        out.setLevel(ZipOutputStream.DEFLATED);
    } else {
        out.setLevel(ZipOutputStream.STORED);
    }
    // copy contents of old jar to new jar:
    JarFile inputFile = new JarFile(jarFile);
    JarInputStream in = new JarInputStream(new FileInputStream(jarFile));
    CRC32 crc = new CRC32();
    byte[] buffer = new byte[512 * 1024];
    JarEntry entry = (JarEntry) in.getNextEntry();
    while (entry != null) {
        InputStream entryIn = inputFile.getInputStream(entry);
        add(entry, entryIn, out, crc, buffer);
        entryIn.close();
        entry = (JarEntry) in.getNextEntry();
    }
    in.close();
    inputFile.close();

    int sourceDirLength;
    if (parentDir == null) {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1;
    } else {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1
                - parentDir.getAbsolutePath().length();
    }
    addFile(file, out, crc, sourceDirLength, buffer);
    out.close();

    // remove old jar file and rename temp file to old one:
    if (jarFile.delete()) {
        if (!tmpJarFile.renameTo(jarFile)) {
            throw new IOException(
                    "Unable to rename temporary JAR file to [" + jarFile.getAbsolutePath() + "].");
        }
    } else {
        throw new IOException("Unable to delete old JAR file [" + jarFile.getAbsolutePath() + "].");
    }

}

From source file:net.mybox.mybox.ServerClientConnection.java

private void handleInput(Common.Signal input) {

    Server.printMessage("(" + Common.now() + ") Client " + handle + ": " + input.toString());

    if (input == Common.Signal.c2s) {
        try {//from  w w  w.  j  a v a 2 s.c om
            String fileName = ByteStream.toString(inStream);
            String fileTimeString = ByteStream.toString(inStream);

            // TODO: create underlying directory if the file needs it

            long fileTime = Long.valueOf(fileTimeString);
            System.out.println("getting file: " + fileName + " modtime " + fileTime);
            File file = new File(localDir + "/" + fileName);
            ByteStream.toFile(inStream, file);

            if (!file.setLastModified(fileTime)) {
                System.err.println("Unable to set file modification time");
                System.exit(1);
            }

            server.spanCatchupOperation(handle, account.id, input, fileName);
        } catch (Exception e) {
            System.out.println(input.toString() + " operation failed: " + e.getMessage());
        }
    } else if (input == Common.Signal.clientWantsToSend) {
        try {
            String fileName = ByteStream.toString(inStream);
            String fileTimeString = ByteStream.toString(inStream);
            long fileTime = Long.valueOf(fileTimeString);

            System.out.println("clientWantsToSend: " + fileName + " modtime " + fileTime);
            File file = new File(localDir + "/" + fileName);

            sendCommandToClient(Common.Signal.clientWantsToSend_response);
            ByteStream.toStream(outStream, fileName);

            // reply 'yes' if it refers to a file that does not exist or if the times do not match
            if (file.isFile() && file.lastModified() == fileTime) {
                ByteStream.toStream(outStream, "no");
            } else {
                ByteStream.toStream(outStream, "yes");
            }
        } catch (Exception e) {
            System.out.println(input.toString() + " operation failed: " + e.getMessage());
        }
    } else if (input == Common.Signal.clientWants) {
        try {
            String fileName = ByteStream.toString(inStream);
            System.out.println("client requesting from server: " + fileName);
            File file = new File(localDir + "/" + fileName);
            if (file.exists()) {
                outQueue.push(new MyFile(fileName, 10, "file"));
                checkQueue();
            }
        } catch (Exception e) {
            System.out.println(input.toString() + " operation failed: " + e.getMessage());
        }
    } else if (input == Common.Signal.deleteOnServer) { // handles files and directories
        try {
            String fileName = ByteStream.toString(inStream);
            System.out.println("client requested deletion on server: " + fileName);
            File item = new File(localDir + "/" + fileName);
            if (item.isDirectory())
                Common.deleteLocalDirectory(item);
            else if (item.exists()) // assume it is a file
                item.delete();
            else
                System.out.println("unable to find item on server to delete");

            server.spanCatchupOperation(handle, account.id, input, fileName);
        } catch (Exception e) {
            System.out.println(input.toString() + " operation failed: " + e.getMessage());
        }
    } else if (input == Common.Signal.renameOnServer) { // handles files and directories
        try {
            String oldName = ByteStream.toString(inStream);
            String newName = ByteStream.toString(inStream);
            System.out.println("client requested rename on server: (" + oldName + ") to (" + newName + ")");
            File oldFile = new File(localDir + "/" + oldName);
            File newFile = new File(localDir + "/" + newName);
            if (oldFile.exists()) {
                oldFile.renameTo(newFile);
            }

            server.spanCatchupOperation(handle, account.id, input, oldName + "->" + newName);

        } catch (Exception e) {
            System.out.println(input.toString() + " operation failed: " + e.getMessage());
        }
    } else if (input == Common.Signal.createDirectoryOnServer) {
        try {
            String name = ByteStream.toString(inStream);
            System.out.println("client requesting create directory on server: " + name);
            Common.createLocalDirectory(localDir + "/" + name);

            // update database
            //        preparedInsert = connection.prepareStatement("insert or ignore into archive values(?,?,?);");
            //        preparedInsert.setString(1, name);
            //        preparedInsert.setString(2, "d");
            //        preparedInsert.setLong(3, (new Date()).getTime());
            //        preparedInsert.executeUpdate(); // TODO: check return number before continuing
            //        connection.commit();

            server.spanCatchupOperation(handle, account.id, input, name);
        } catch (Exception e) {
            System.out.println(input.toString() + " operation failed: " + e.getMessage());
            System.exit(1);
        }
    } else if (input == Common.Signal.requestServerFileList) {
        sendServerFileList();
    } else if (input == Common.Signal.attachaccount) {

        String args = null;

        try {
            args = ByteStream.toString(inStream);
        } catch (Exception e) {
            //
        }

        HashMap attachInput = Common.jsonDecode(args);
        String email = (String) attachInput.get("email");
        //        String password = (String)attachInput.get("password");

        JSONObject jsonOut = new JSONObject();
        jsonOut.put("serverMyboxVersion", Common.appVersion);

        if (attachAccount(email)) {
            jsonOut.put("status", "success");
            jsonOut.put("quota", account.quota);
            jsonOut.put("salt", account.salt);

            server.updateMultiMap(account.id, handle);
        } else {
            jsonOut.put("status", "failed");
            jsonOut.put("error", "invalid account");
        }

        try {
            sendCommandToClient(Common.Signal.attachaccount_response);
            ByteStream.toStream(outStream, jsonOut.toJSONString());
        } catch (Exception e) {
            //
        }

        Server.printMessage("attachaccount_response: " + jsonOut);

    } else {
        Server.printMessage("unknown command: " + input);
        failedRequestCount++;
    }

}

From source file:com.tealeaf.Downloader.java

protected boolean cache(String name, File contents) {
    logger.log("{downloader} Caching", contents.getAbsolutePath(), "to", name);
    int i = name.lastIndexOf("/");
    if (i >= 0) {
        File directory = new File(name.substring(0, i));
        if (!directory.exists() && !directory.mkdirs()) {
            // if we can't make the subdirectories, don't even bother trying to cache
            logger.log("{downloader} ERROR: Unable to make directory", directory.getName());
            return false;
        }/*from   www  . j a v a2 s  .c  om*/
    }
    File file = new File(name);
    file.delete();
    try {
        file.createNewFile();
        if (!contents.renameTo(file)) {
            logger.log("{downloader} ERROR: Unable to rename file", name);
        }
    } catch (Exception e) {
        logger.log(e);
    }
    return true;
}