List of usage examples for java.io File renameTo
public boolean renameTo(File dest)
From source file:com.mirth.connect.connectors.file.filesystems.FileConnection.java
@Override public void move(String fromName, String fromDir, String toName, String toDir) throws FileConnectorException { File src = new File(fromDir, fromName); File dst = new File(toDir, toName); dst.delete();//from w w w.ja v a 2s . c o m // File.renameTo operation doesn't work across file systems. So we will // attempt to do a File.renameTo for efficiency and atomicity, if this // fails then we will use the Commons-IO moveFile operation which // does a "copy and delete" if (!src.renameTo(dst)) { try { // Copy the file FileUtils.copyFile(src, dst); // This will NOT throw any exceptions, this only return // true/false if (!FileUtils.deleteQuietly(src)) { // We had a problem, so now we should ignore it ignoreFile(src); } } catch (IOException e) { throw new FileConnectorException( "Error from file from [" + src.getAbsolutePath() + "] to [" + dst.getAbsolutePath() + "]", e); } } }
From source file:com.adaptris.core.fs.FsProducer.java
protected void write(AdaptrisMessage msg, File destFile) throws Exception { File fileToWriteTo = destFile; if (getTempDirectory() != null) { File tmpFile = createTempFile(msg); log.trace("Writing to temporary file " + tmpFile.getCanonicalPath()); fileToWriteTo = tmpFile;//from w ww . j a va2s . c o m } fsWorker.put(encode(msg), fileToWriteTo); if (getTempDirectory() != null) { log.trace("Renaming temporary file to " + destFile.getCanonicalPath()); fileToWriteTo.renameTo(destFile); } }
From source file:com.alibaba.antx.config.resource.DefaultAuthenticationHandler.java
private boolean savePasswordFile(Properties passwords) throws IOException, FileNotFoundException { File tmp = File.createTempFile(passwordFile.getName() + ".", ".tmp", passwordFile.getParentFile()); OutputStream os = null;//from w w w. j a v a2s. c om tmp.deleteOnExit(); try { os = new FileOutputStream(tmp); passwords.store(os, "Passwords for antxconfig"); } finally { if (os != null) { try { os.close(); } catch (IOException e) { } } } passwordFile.delete(); return tmp.renameTo(passwordFile); }
From source file:com.zimbra.cs.store.file.BlobDeduper.java
private Pair<Integer, Long> deDupe(List<BlobReference> blobs) throws ServiceException { int linksCreated = 0; long sizeSaved = 0; long srcInodeNum = 0; String srcPath = null;/*w w w . j a v a2s . co m*/ // check if there is any processed blob for (BlobReference blob : blobs) { if (blob.isProcessed()) { String path = FileBlobStore.getBlobPath(blob.getMailboxId(), blob.getItemId(), blob.getRevision(), blob.getVolumeId()); try { IO.FileInfo fileInfo = IO.fileInfo(path); if (fileInfo != null) { srcInodeNum = fileInfo.getInodeNum(); srcPath = path; break; } } catch (IOException e) { // ignore } } } if (srcInodeNum == 0) { // check the path with maximum links // organize the paths based on inode MultiMap inodeMap = new MultiValueMap(); for (BlobReference blob : blobs) { String path = FileBlobStore.getBlobPath(blob.getMailboxId(), blob.getItemId(), blob.getRevision(), blob.getVolumeId()); try { IO.FileInfo fileInfo = IO.fileInfo(path); if (fileInfo != null) { inodeMap.put(fileInfo.getInodeNum(), path); blob.setFileInfo(fileInfo); } } catch (IOException e) { // ignore } } // find inode which has maximum paths int maxPaths = 0; @SuppressWarnings("unchecked") Iterator<Map.Entry<Long, Collection<String>>> iter = inodeMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Long, Collection<String>> entry = iter.next(); if (entry.getValue().size() > maxPaths) { maxPaths = entry.getValue().size(); srcInodeNum = entry.getKey(); srcPath = entry.getValue().iterator().next(); } } } if (srcInodeNum == 0) { return new Pair<Integer, Long>(0, Long.valueOf(0)); } // First create a hard link for the source path, so that the file // doesn't get deleted in the middle. String holdPath = srcPath + "_HOLD"; File holdFile = new File(holdPath); try { IO.link(srcPath, holdPath); // Now link the other paths to source path for (BlobReference blob : blobs) { if (blob.isProcessed()) { continue; } String path = FileBlobStore.getBlobPath(blob.getMailboxId(), blob.getItemId(), blob.getRevision(), blob.getVolumeId()); try { if (blob.getFileInfo() == null) { blob.setFileInfo(IO.fileInfo(path)); } } catch (IOException e) { // ignore } if (blob.getFileInfo() == null) { continue; } if (srcInodeNum == blob.getFileInfo().getInodeNum()) { markBlobAsProcessed(blob); continue; } // create the links for paths in two steps. // first create a temp link and then rename it to actual path // this guarantees that the file is always available. String tempPath = path + "_TEMP"; File tempFile = new File(tempPath); try { IO.link(holdPath, tempPath); File destFile = new File(path); tempFile.renameTo(destFile); markBlobAsProcessed(blob); linksCreated++; sizeSaved += blob.getFileInfo().getSize(); } catch (IOException e) { ZimbraLog.misc.warn("Ignoring the error while deduping " + path, e); } finally { if (tempFile.exists()) { tempFile.delete(); } } } } catch (IOException e) { ZimbraLog.misc.warn("Ignoring the error while creating a link for " + srcPath, e); } finally { // delete the hold file if (holdFile.exists()) { holdFile.delete(); } } return new Pair<Integer, Long>(linksCreated, sizeSaved); }
From source file:net.bitjump.launchme.utils.FileConfig.java
private boolean mismatchVersion(File cFile) { File bFile = new File(new StringBuilder().append(plugin.getDataFolder()).append(File.separator) .append("config.backup.yml").toString()); YamlConfiguration configV = YamlConfiguration.loadConfiguration(cFile); if (!configV.contains("version") || !configV.getString("version").equals(plugin.getConfig().getDefaults().getString("version"))) { if (bFile.exists()) { bFile.delete();//from w w w.j av a2 s . com } cFile.renameTo(bFile); MessageUtils.showMessage(ChatColor.RED + "Mismatch config version, a new one has been created."); backupFile = bFile; return true; } return false; }
From source file:com.netscape.cms.publish.publishers.FileBasedPublisher.java
private void createLink(String linkName, String fileName) { String cmd = "ln -s " + fileName + " " + linkName + ".new"; if (com.netscape.cmsutil.util.Utils.exec(cmd)) { File oldLink = new File(linkName + ".old"); if (oldLink.exists()) { // remove old link if exists oldLink.delete();//from w ww. j a v a 2 s . com } File link = new File(linkName); if (link.exists()) { // current link becomes an old link link.renameTo(new File(linkName + ".old")); } File newLink = new File(linkName + ".new"); if (newLink.exists()) { // new link becomes current link newLink.renameTo(new File(linkName)); } oldLink = new File(linkName + ".old"); if (oldLink.exists()) { // remove a new old link oldLink.delete(); } } else { CMS.debug("FileBasedPublisher: createLink: '" + cmd + "' --- failed"); } }
From source file:com.w4t.engine.requests.UploadRequestFileItem.java
/** * <p>a convenience method to write an uploaded item to disk. The client code * is not concerned with whether or not the item is stored in memory, or on * disk in a temporary location. They just want to write the uploaded item to * a file.</p>//from w w w. j a va 2s.com * * <p>This implementation first attempts to rename the uploaded item to the * specified destination file, if the item was originally written to disk. * Otherwise, the data will be copied to the specified file.</p> * * <p>This method is only guaranteed to work <em>once</em>, the first time it * is invoked for a particular item. This is because, in the event that the * method renames a temporary file, that file will no longer be available to * copy or rename again at a later time.</p> * * @param file The <code>File</code> into which the uploaded item should be * stored. * @exception Exception if an error occurs. */ public void write(final File file) throws IOException { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { /* * The uploaded file is being stored on disk in a temporary location so * move it to the desired file. */ if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); byte[] bytes = new byte[2048]; int s = 0; while ((s = in.read(bytes)) != -1) { out.write(bytes, 0, s); } } finally { try { if (in != null) { in.close(); } } catch (IOException e) { // ignore } try { if (out != null) { out.close(); } } catch (IOException e) { // ignore } } } } else { /* * For whatever reason we cannot write the file to disk. */ throw new IOException("Cannot write uploaded file to disk!"); } } }
From source file:com.clutch.ClutchSync.java
private static void complete(File tempDir, JSONObject files) { String versionName = ""; try {//from w ww . ja v a 2 s . c o m versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; } catch (NameNotFoundException e) { Log.e(TAG, "Could not get bundle version"); e.printStackTrace(); } if (newFilesDownloaded) { File dir = context.getDir("_clutch" + versionName, 0); // Write out __files.json OutputStream outFilesList; try { outFilesList = new FileOutputStream(new File(tempDir, "__files.json")); outFilesList.write(files.toString().getBytes()); outFilesList.flush(); outFilesList.close(); } catch (FileNotFoundException e) { Log.e(TAG, "Could not write out the Clutch files hash cache: " + e); thisIsHappening = false; return; } catch (IOException e) { Log.e(TAG, "Could not write out the Clutch files hash cache: " + e); thisIsHappening = false; return; } deleteDir(dir); if (!tempDir.renameTo(dir)) { Log.e(TAG, "Could not rename " + tempDir.getPath() + " to " + dir.getPath()); } ClutchConf.setConf(null); // In ObjC we actually write the contents of the conf in setConf // Let's see if this works. ClutchConf.getConf(); if (conf.optBoolean("_dev") || newFilesDownloaded) { pendingReload = true; } if (conf.optBoolean("_dev")) { for (ClutchView clutchView : clutchViews) { clutchView.contentChanged(); } if (!conf.optBoolean("_toolbar")) { shouldWatchForChanges = true; watchForChanges(); } } } thisIsHappening = false; }
From source file:com.filelocker.encryption.AES_Encryption.java
/** * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). * We have the password from initializing the class. pass the iv and salt here which is * obtained when encrypting the file initially. * * @param inFile - The Encrypted File containing encrypted data , salt and InitVec * @throws NoSuchAlgorithmException/*from www . j a va 2s.c om*/ * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws DecoderException * @throws IOException */ public void setupDecrypt(File inFile) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException, IOException { SecretKeyFactory factory = null; SecretKey tmp = null; SecretKey secret = null; byte[] vSalt = new byte[8]; byte[] vInitVec = new byte[16]; RandomAccessFile vFile = new RandomAccessFile(inFile, "rw"); //The last 8 bits are salt so seek to length of file minus 9 bits vFile.seek(vFile.length() - 8); vFile.readFully(vSalt); //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24 //Thus to seek to length of file minus 24 bits vFile.seek(vFile.length() - 24); vFile.readFully(vInitVec); vFile.seek(0); File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file"); RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw"); for (int i = 0; i < (vFile.length() - 24); ++i) { vTmpFile.write(vFile.readByte()); } vFile.close(); vTmpFile.close(); inFile.delete(); tmpFile.renameTo(inFile); Db("got salt " + Hex.encodeHexString(vSalt)); Db("got initvector :" + Hex.encodeHexString(vInitVec)); /* Derive the key, given password and salt. */ // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" // The end user must also install them (not compiled in) so beware. // see here: // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard) factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); // Decrypt the message, given derived key and initialization vector. vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec)); }