synchronized void migrateData(DataStore targetStore) { ForceLoadAllClaims(this); targetStore.ClearInventoryOnJoinPlayers = ClearInventoryOnJoinPlayers; // migrate claims for (Claim c : this.claims) { GriefPrevention.AddLogEntry("Migrating Claim #" + c.getID()); targetStore.addClaim(c); } // migrate groups Iterator<String> groupNamesEnumerator = this.permissionToBonusBlocksMap.keySet().iterator(); while (groupNamesEnumerator.hasNext()) { String groupName = groupNamesEnumerator.next(); targetStore.saveGroupBonusBlocks(groupName, this.permissionToBonusBlocksMap.get(groupName)); } // migrate players for (PlayerData pdata : getAllPlayerData()) { targetStore.playerNameToPlayerDataMap.put(pdata.playerName, pdata); targetStore.savePlayerData(pdata.playerName, pdata); } // migrate next claim ID if (this.nextClaimID > targetStore.nextClaimID) { targetStore.setNextClaimID(this.nextClaimID); } // rename player and claim data folders so the migration won't run again int i = 0; File claimsBackupFolder; File playersBackupFolder; do { String claimsFolderBackupPath = claimDataFolderPath; if (i > 0) claimsFolderBackupPath += String.valueOf(i); claimsBackupFolder = new File(claimsFolderBackupPath); String playersFolderBackupPath = playerDataFolderPath; if (i > 0) playersFolderBackupPath += String.valueOf(i); playersBackupFolder = new File(playersFolderBackupPath); i++; } while (claimsBackupFolder.exists() || playersBackupFolder.exists()); File claimsFolder = new File(claimDataFolderPath); File playersFolder = new File(playerDataFolderPath); claimsFolder.renameTo(claimsBackupFolder); playersFolder.renameTo(playersBackupFolder); GriefPrevention.AddLogEntry( "Backed your file system data up to " + claimsBackupFolder.getName() + " and " + playersBackupFolder.getName() + "."); GriefPrevention.AddLogEntry( "If your migration encountered any problems, you can restore those data with a quick copy/paste."); GriefPrevention.AddLogEntry( "When you're satisfied that all your data have been safely migrated, consider deleting those folders."); }
/** Save the contents of the FS image */ void saveFSImage(File fullimage, File edits) throws IOException { File curFile = new File(fullimage, FS_IMAGE); File newFile = new File(fullimage, NEW_FS_IMAGE); File oldFile = new File(fullimage, OLD_FS_IMAGE); // // Write out data // DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(newFile))); try { out.writeInt(rootDir.numItemsInTree() - 1); rootDir.saveImage("", out); } finally { out.close(); } // // Atomic move sequence // // 1. Move cur to old curFile.renameTo(oldFile); // 2. Move new to cur newFile.renameTo(curFile); // 3. Remove pending-edits file (it's been integrated with newFile) edits.delete(); // 4. Delete old oldFile.delete(); }
private File addBlock(Block b, File src, boolean createOk, boolean resetIdx) throws IOException { if (numBlocks < maxBlocksPerDir) { File dest = new File(dir, b.getBlockName()); File metaData = getMetaFile(src, b); File newmeta = getMetaFile(dest, b); if (!metaData.renameTo(newmeta) || !src.renameTo(dest)) { throw new IOException( "could not move files for " + b + " from tmp to " + dest.getAbsolutePath()); } if (DataNode.LOG.isDebugEnabled()) { DataNode.LOG.debug("addBlock: Moved " + metaData + " to " + newmeta); DataNode.LOG.debug("addBlock: Moved " + src + " to " + dest); } numBlocks += 1; return dest; } if (lastChildIdx < 0 && resetIdx) { // reset so that all children will be checked lastChildIdx = random.nextInt(children.length); } if (lastChildIdx >= 0 && children != null) { // Check if any child-tree has room for a block. for (int i = 0; i < children.length; i++) { int idx = (lastChildIdx + i) % children.length; File file = children[idx].addBlock(b, src, false, resetIdx); if (file != null) { lastChildIdx = idx; return file; } } lastChildIdx = -1; } if (!createOk) { return null; } if (children == null || children.length == 0) { children = new FSDir[maxBlocksPerDir]; for (int idx = 0; idx < maxBlocksPerDir; idx++) { children[idx] = new FSDir(new File(dir, DataStorage.BLOCK_SUBDIR_PREFIX + idx)); } } // now pick a child randomly for creating a new set of subdirs. lastChildIdx = random.nextInt(children.length); return children[lastChildIdx].addBlock(b, src, true, false); }
public void saveCache( JMXInstrumentedCache<K, V> cache, File savedCachePath, Function<K, byte[]> converter) throws IOException { long start = System.currentTimeMillis(); String msgSuffix = " " + savedCachePath.getName() + " for " + cfname + " of " + ksname; logger.debug("saving" + msgSuffix); int count = 0; File tmpFile = File.createTempFile(savedCachePath.getName(), null, savedCachePath.getParentFile()); FileOutputStream fout = new FileOutputStream(tmpFile); ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fout)); FileDescriptor fd = fout.getFD(); for (K key : cache.getKeySet()) { byte[] bytes = converter.apply(key); out.writeInt(bytes.length); out.write(bytes); ++count; } out.flush(); fd.sync(); out.close(); if (!tmpFile.renameTo(savedCachePath)) throw new IOException("Unable to rename cache to " + savedCachePath); if (logger.isDebugEnabled()) logger.debug( "saved " + count + " keys in " + (System.currentTimeMillis() - start) + " ms from" + msgSuffix); }
/** Maintain the versions of the file we are about to for writing. */ private static boolean shuffleVersions(String file) { File f = new File(file); if (!f.exists()) { return true; } int version = 99; boolean found = false; do { String fileVersion = file + String.format("_%02d", version); File vf = new File(fileVersion); if (vf.exists()) { found = true; } else { version--; } } while (!found && version >= 0); version++; String fileVersion = file + String.format("_%02d", version); File newf = new File(fileVersion); return f.renameTo(newf); }
private void saveConfiguration( BundleInfo[] configuration, File outputFile, URI installArea, boolean backup) throws IOException { if (backup && outputFile.exists()) { File backupFile = Utils.getSimpleDataFormattedFile(outputFile); if (!outputFile.renameTo(backupFile)) { throw new IOException("Fail to rename from (" + outputFile + ") to (" + backupFile + ")"); } } org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo[] simpleInfos = convertBundleInfos(configuration, installArea); // if empty remove the configuration file if (simpleInfos == null || simpleInfos.length == 0) { if (outputFile.exists()) { outputFile.delete(); } File parentDir = outputFile.getParentFile(); if (parentDir.exists()) { parentDir.delete(); } return; } SimpleConfiguratorManipulatorUtils.writeConfiguration(simpleInfos, outputFile); if (CONFIG_LIST.equals(outputFile.getName()) && installArea != null && isSharedInstallSetup(URIUtil.toFile(installArea), outputFile)) rememberSharedBundlesInfoTimestamp(installArea, outputFile.getParentFile()); }
@NotNull private String createLocalFile(@NotNull ObjectId id, @NotNull ObjectLoader loader) throws IOException { // Create LFS stream. final File tmpFile = new File(tempPath, UUID.randomUUID().toString()); final MessageDigest md = createSha256(); try (InputStream istream = loader.openStream(); OutputStream ostream = new FileOutputStream(tmpFile)) { byte[] buffer = new byte[0x10000]; while (true) { int size = istream.read(buffer); if (size <= 0) break; ostream.write(buffer, 0, size); md.update(buffer, 0, size); } } final String hash = new String(Hex.encodeHex(md.digest(), true)); cacheSha256.putIfAbsent(id.name(), hash); cache.commit(); // Rename file. final File lfsFile = new File( basePath, "lfs/objects/" + hash.substring(0, 2) + "/" + hash.substring(2, 4) + "/" + hash); makeParentDirs(lfsFile.getParentFile()); if (lfsFile.exists()) { if (!tmpFile.delete()) { log.warn("Can't delete temporary file: {}", lfsFile.getAbsolutePath()); } } else if (!tmpFile.renameTo(lfsFile)) { throw new IOException("Can't rename file: " + tmpFile + " -> " + lfsFile); } return hash; }
private void copyAllFilesToLogDir(File node, File parent) throws IOException { if (!node.getAbsoluteFile().equals(parent.getAbsoluteFile()) && node.isFile() && !node.getParentFile().equals(parent)) { String fileNamePrefix = node.getName().substring(0, node.getName().lastIndexOf('.')); String fileNameSuffix = node.getName().substring(node.getName().lastIndexOf('.')); String newFilePath = node.getParentFile().getAbsolutePath() + File.separator + fileNamePrefix.replace(".", "_") + fileNameSuffix; File newNode = new File(newFilePath); if (node.renameTo(newNode)) { FileUtils.copyFileToDirectory(newNode, parent); } } if (node.isDirectory()) { String[] subNote = node.list(); for (String filename : subNote) { copyAllFilesToLogDir(new File(node, filename), parent); } if (!node.equals(parent)) { FileUtils.deleteDirectory(node); } } }
public static void rename(@NotNull File source, @NotNull File target) throws IOException { if (source.renameTo(target)) return; if (!source.exists()) return; copy(source, target); delete(source); }
public void renameDataSourceDir(String oldDataSourceId, String newDataSourceId) throws FileNotFoundException, IOException { File dataSourceDir = getDataSourceDir(oldDataSourceId); if (dataSourceDir.exists()) { dataSourceDir.renameTo(getDataSourceDir(newDataSourceId)); } }
public static boolean moveDirWithContent(@NotNull File fromDir, @NotNull File toDir) { if (!toDir.exists()) return fromDir.renameTo(toDir); File[] files = fromDir.listFiles(); if (files == null) return false; boolean success = true; for (File fromFile : files) { File toFile = new File(toDir, fromFile.getName()); success = success && fromFile.renameTo(toFile); } fromDir.delete(); return success; }
private static void preserveFiles(String filename) { File oldFile = new File(filename); File saveFile = new File(filename + ".temp"); SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyy_HHmm"); String nowStr = sdf.format(new Date()); String retainFilename = makeBackupFilename(filename, nowStr); File retainFile = new File(retainFilename); if (retainFile.exists()) retainFile.delete(); String oldestSave = JConfig.queryConfiguration("save.file.4", ""); if (oldestSave.length() != 0) { File oldest = new File(oldestSave); if (oldest.exists()) { backupByDate(filename, oldest); } } for (int i = 4; i > 0; i--) { JConfig.setConfiguration( "save.file." + i, JConfig.queryConfiguration("save.file." + (i - 1), "")); } File keepFile = new File(retainFilename); if (!oldFile.renameTo(keepFile)) { JConfig.log() .logDebug( "Renaming the old file (" + oldFile + ") to the retain file (" + keepFile + ") failed!"); } JConfig.setConfiguration("save.file.0", retainFilename); File standard = new File(filename); if (!saveFile.renameTo(standard)) { JConfig.log() .logDebug( "Renaming the new file (" + saveFile + ") to the standard filename (" + standard + ") failed!"); } }
public static void main(final String[] args) { final File targetFile = new File("D:\\abc.def"); final File tmp = new File(targetFile.getPath() + ".frftmp"); if (!FileAccess.compressFileGZip(targetFile, tmp)) { return; // error } targetFile.delete(); tmp.renameTo(targetFile); }
/** * Load in the filesystem image. It's a big list of filenames and blocks. Return whether we should * "re-save" and consolidate the edit-logs */ boolean loadFSImage(File fsdir, File edits) throws IOException { // // Atomic move sequence, to recover from interrupted save // File curFile = new File(fsdir, FS_IMAGE); File newFile = new File(fsdir, NEW_FS_IMAGE); File oldFile = new File(fsdir, OLD_FS_IMAGE); // Maybe we were interrupted between 2 and 4 if (oldFile.exists() && curFile.exists()) { oldFile.delete(); if (edits.exists()) { edits.delete(); } } else if (oldFile.exists() && newFile.exists()) { // Or maybe between 1 and 2 newFile.renameTo(curFile); oldFile.delete(); } else if (curFile.exists() && newFile.exists()) { // Or else before stage 1, in which case we lose the edits newFile.delete(); } // // Load in bits // if (curFile.exists()) { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(curFile))); try { int numFiles = in.readInt(); for (int i = 0; i < numFiles; i++) { UTF8 name = new UTF8(); name.readFields(in); int numBlocks = in.readInt(); if (numBlocks == 0) { unprotectedAddFile(name, null); } else { Block blocks[] = new Block[numBlocks]; for (int j = 0; j < numBlocks; j++) { blocks[j] = new Block(); blocks[j].readFields(in); } unprotectedAddFile(name, blocks); } } } finally { in.close(); } } if (edits.exists() && loadFSEdits(edits) > 0) { return true; } else { return false; } }
/** * 코드저장소 프로젝트명을 변경하고 결과를 반환한다. * * @param projectName * @return 코드저장소 이름 변경성공시 true / 실패시 false */ @Override public boolean renameTo(String projectName) { File src = new File(getRepoPrefix() + this.ownerName + "/" + this.projectName); File dest = new File(getRepoPrefix() + this.ownerName + "/" + projectName); src.setWritable(true); return src.renameTo(dest); }
public void setFileName(int row, String name) { // avoid moving a File by renaming it !! if (name.indexOf("..") < 0 && name.indexOf("/") < 0 && name.indexOf("\\") < 0) { File oldFile = getFile(filenames[row]); File newFile = new File(oldFile.getParent() + File.separator + name); filenames[row] = name; oldFile.renameTo(newFile); } }
/** * Loop through the ZIP file, copying its entries into a new, temporary ZIP file, skipping the * entry to be deleted. Then replace the original file with the new one. */ protected Integer deleteEntry() throws XMLDataStoreException { try { ZipInputStream inStream = this.buildZipInputStream(); File outFile = this.buildTempFile(); ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(outFile)); byte[] buffer = new byte[32768]; int inCount = 0; int outCount = 0; // copy all the entries except the one to be deleted ZipEntry entry = inStream.getNextEntry(); while (entry != null) { inCount++; if (!this.getZipEntryName().equals(entry.getName())) { outCount++; outStream.putNextEntry(entry); int byteCount; while ((byteCount = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, byteCount); } outStream.closeEntry(); } entry = inStream.getNextEntry(); } inStream.close(); if (outCount == 0) { // add a dummy record to an empty file so we can close it // this is required by ZipOutputStream outStream.putNextEntry(new ZipEntry("delete.txt")); outStream.write( "This file is a place-holder. The containing ZIP file should be deleted.".getBytes()); outStream.closeEntry(); } outStream.close(); if (outCount == inCount) { // no entries were removed - just delete the temp file outFile.delete(); } else { // at least one entry removed - delete the original file this.getFile().delete(); if (outCount == 0) { // NO entries remain - just delete the temp file too outFile.delete(); } else { // entries remain - replace original file with temp file outFile.renameTo(this.getFile()); } } return new Integer(inCount - outCount); // should be 0 or 1 } catch (IOException ex) { throw XMLDataStoreException.ioException(ex); } }
private void checkAndLaunchUpdate() { Log.i(LOG_FILE_NAME, "Checking for an update"); int statusCode = 8; // UNEXPECTED_ERROR File baseUpdateDir = null; if (Build.VERSION.SDK_INT >= 8) baseUpdateDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); else baseUpdateDir = new File(Environment.getExternalStorageDirectory().getPath(), "download"); File updateDir = new File(new File(baseUpdateDir, "updates"), "0"); File updateFile = new File(updateDir, "update.apk"); File statusFile = new File(updateDir, "update.status"); if (!statusFile.exists() || !readUpdateStatus(statusFile).equals("pending")) return; if (!updateFile.exists()) return; Log.i(LOG_FILE_NAME, "Update is available!"); // Launch APK File updateFileToRun = new File(updateDir, getPackageName() + "-update.apk"); try { if (updateFile.renameTo(updateFileToRun)) { String amCmd = "/system/bin/am start -a android.intent.action.VIEW " + "-n com.android.packageinstaller/.PackageInstallerActivity -d file://" + updateFileToRun.getPath(); Log.i(LOG_FILE_NAME, amCmd); Runtime.getRuntime().exec(amCmd); statusCode = 0; // OK } else { Log.i(LOG_FILE_NAME, "Cannot rename the update file!"); statusCode = 7; // WRITE_ERROR } } catch (Exception e) { Log.i(LOG_FILE_NAME, "error launching installer to update", e); } // Update the status file String status = statusCode == 0 ? "succeeded\n" : "failed: " + statusCode + "\n"; OutputStream outStream; try { byte[] buf = status.getBytes("UTF-8"); outStream = new FileOutputStream(statusFile); outStream.write(buf, 0, buf.length); outStream.close(); } catch (Exception e) { Log.i(LOG_FILE_NAME, "error writing status file", e); } if (statusCode == 0) System.exit(0); }
private static void backupByDate(String filename, File oldest) { SimpleDateFormat justDateFmt = new SimpleDateFormat("ddMMMyy"); String justDate = justDateFmt.format(new Date()); String oldBackup = makeBackupFilename(filename, justDate); File oldDateBackup = new File(oldBackup); if (oldDateBackup.exists()) { oldDateBackup.delete(); File newDateBackup = new File(oldBackup); oldest.renameTo(newDateBackup); } else { oldest.renameTo(oldDateBackup); String oldestByDate = JConfig.queryConfiguration("save.bydate.4", ""); for (int i = 4; i > 0; i--) { JConfig.setConfiguration( "save.bydate." + i, JConfig.queryConfiguration("save.bydate." + (i - 1), "")); } JConfig.setConfiguration("save.bydate.0", oldBackup); File deleteMe = new File(oldestByDate); deleteMe.delete(); } }
private void saveData(TelemetryData data) { PrintWriter out; boolean newFile = false; if (saveCnt > 25000) { File logFile; int i; logFile = new File(telemetryDir + 99 + ".log"); logFile.delete(); newFile = true; for (i = 99; i > 0; i--) { logFile = new File(telemetryDir + (i - 1) + ".log"); logFile.renameTo(new File(telemetryDir + i + ".log")); } saveCnt = 0; } try { String text = ""; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.GERMAN); saveCnt++; out = new PrintWriter(new FileOutputStream(telemetryDir + "0.log", true)); if (newFile) { text = "Time\tLatitude\tLongitude\tSpeed\tAcceleration X\tAcceleration Y\tAcceleration Z\tCoG\tOrientation Y\tOrientation Z\n\n"; out.print(text); } text = dateFormat.format(new Date(System.currentTimeMillis())) + "\t"; if (posValid) text = text + lastLat + "\t" + lastLon + "\t" + m_lastSpeed + "\t"; else text = text + "-\t-\t-\t"; text = text + data.getAccelX() + "\t" + data.getAccelY() + "\t" + data.getAccelZ() + "\t" + data.CoG + "\t" + data.getOrientY() + "\t" + data.getOrientZ() + "\n\n"; out.print(text); out.close(); } catch (IOException ioe) { } }
private void tidyFileAway(File f, String extension) { File rename = new File(f.getAbsolutePath() + "." + extension); while (rename.exists()) { rename = new File(rename.getAbsolutePath() + "." + extension); } getLog() .warn( "Tidying " + f.getAbsolutePath() + " out of the way, by adding ." + extension, "It will be called: " + rename.getAbsolutePath() + " see log above for detail of problem."); f.renameTo(rename); }
private void seizeExternal() { try { File srcFile = new File(mmPath); File destFile = new File(mContext.getExternalFilesDir(null), srcFile.getName()); if (!srcFile.renameTo(destFile)) { throw new IOException( String.format( "cannot rename %s to %s", srcFile.getAbsolutePath(), destFile.getAbsolutePath())); } mmPath = destFile.getAbsolutePath(); } catch (IOException e) { throw new RuntimeException(e); } }
/** * (Re)generate the target {@linkplain Properties properties} file. * * @throws IOException If an exceptional situation arises while reading properties. */ public void generate() throws IOException { // Force correct initialization order... sigh. AvailRuntime.nextHash(); final File fileName = new File( String.format( "src/%s_%s.properties", baseName.replace('.', '/'), locale.getLanguage())); System.out.println(fileName.getAbsolutePath()); final String[] components = baseName.split("\\."); final File tempFileName = new File( String.format( "%s/%s_%s.propertiesTEMP", System.getProperty("java.io.tmpdir"), components[components.length - 1], locale.getLanguage())); assert fileName.getPath().endsWith(".properties"); final Properties properties = new Properties(); try (final FileInputStream inputStream = new FileInputStream(fileName)) { try (final InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { properties.load(reader); } } catch (final FileNotFoundException e) { // Ignore. It's okay if the file doesn't already exist. } final PrintWriter writer = new PrintWriter(tempFileName, "UTF-8"); generatePreamble(writer); generateProperties(properties, writer); writer.close(); // Now switch the new file in. In the rare event of failure between // these steps, the complete content will still be available in the // corresponding *.propertiesTEMP file. boolean worked = fileName.delete(); if (!worked) { System.err.println( String.format("deleting the original properties file failed: %s", fileName)); } worked = tempFileName.renameTo(fileName); if (!worked) { throw new RuntimeException( String.format( "moving the temporary properties file failed: %s -> %s", tempFileName, fileName)); } }
/** par: filename for the level.dat_mcr backup */ private void createFile(String par1Str) { File file = new File(savesDirectory, par1Str); if (!file.exists()) { System.out.println("Warning: Unable to create level.dat_mcr backup"); return; } File file1 = new File(file, "level.dat"); if (!file1.exists()) { System.out.println("Warning: Unable to create level.dat_mcr backup"); return; } File file2 = new File(file, "level.dat_mcr"); if (!file1.renameTo(file2)) { System.out.println("Warning: Unable to create level.dat_mcr backup"); } }
private long persist(File f, ObjectName name) { long deployed = f.lastModified(); try { Element e = (Element) server.getAttribute(name, "Persist"); if (e != null) { XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); Document doc = new Document(); e.detach(); doc.setRootElement(e); File tmp = new File(f.getAbsolutePath() + ".tmp"); FileWriter writer = new FileWriter(tmp); out.output(doc, writer); writer.close(); f.delete(); tmp.renameTo(f); deployed = f.lastModified(); } } catch (Exception ex) { log.warn("persist", ex); } return deployed; }
protected void saveState() throws TeamException { IPath pluginStateLocation = CVSUIPlugin.getPlugin().getStateLocation(); File tempFile = pluginStateLocation.append(REPOSITORIES_VIEW_FILE + ".tmp").toFile(); // $NON-NLS-1$ File stateFile = pluginStateLocation.append(REPOSITORIES_VIEW_FILE).toFile(); try { XMLWriter writer = new XMLWriter(new BufferedOutputStream(new FileOutputStream(tempFile))); try { writeState(writer); } finally { writer.close(); } if (stateFile.exists()) { stateFile.delete(); } boolean renamed = tempFile.renameTo(stateFile); if (!renamed) { throw new TeamException( new Status( IStatus.ERROR, CVSUIPlugin.ID, TeamException.UNABLE, NLS.bind( CVSUIMessages.RepositoryManager_rename, new String[] {tempFile.getAbsolutePath()}), null)); } } catch (IOException e) { throw new TeamException( new Status( IStatus.ERROR, CVSUIPlugin.ID, TeamException.UNABLE, NLS.bind( CVSUIMessages.RepositoryManager_save, new String[] {stateFile.getAbsolutePath()}), e)); } }
@Nullable private static File renameToTempFileOrDelete(@NotNull File file) { final File tempDir = new File(getTempDirectory()); boolean isSameDrive = true; if (SystemInfo.isWindows) { String tempDirDrive = tempDir.getAbsolutePath().substring(0, 2); String fileDrive = file.getAbsolutePath().substring(0, 2); isSameDrive = tempDirDrive.equalsIgnoreCase(fileDrive); } if (isSameDrive) { // the optimization is reasonable only if destination dir is located on the same drive final String originalFileName = file.getName(); File tempFile = getTempFile(originalFileName, tempDir); if (file.renameTo(tempFile)) { return tempFile; } } delete(file); return null; }
@Override public void save() { NBTOutputStream stream = null; try { Files.createParentDirs(this.file); final File temporaryFile = File.createTempFile(this.file.getName(), null, this.file.getParentFile()); temporaryFile.deleteOnExit(); stream = new NBTOutputStream(new FileOutputStream(temporaryFile)); stream.writeTag(new CompoundTag(this.name, this.root)); stream.close(); this.file.delete(); temporaryFile.renameTo(this.file); temporaryFile.delete(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { stream.close(); } catch (IOException ex2) { } } }
public static boolean move(File source, File destination) { if (!source.exists()) { return false; } // If both files exists and are equals no need to move it. try { // Confirms that destination exists. if (destination.exists()) { // Creates FileInputStream for both files. FileInputStream inputSource = new FileInputStream(source); FileInputStream inputDestination = new FileInputStream(destination); // Both files checked. if (DigestUtils.md5Hex(inputSource).equals(DigestUtils.md5Hex(inputDestination))) { Logger.info(FileUtil.class, "Move method: Source equal to Destination, no need to move."); return true; } } } catch (Exception e) { // In case of error, no worries. Continued with the same logic of move. Logger.debug(FileUtil.class, "MD5 Checksum failed, continue with standard move"); } destination.delete(); boolean success = source.renameTo(destination); // if the rename fails, copy if (!success) { copyFile(source, destination); success = source.delete(); } return success; }
private void cleanup(File directory) { // Clean up from old installations, removing or renaming files. // Note that directory is the parent of the CTP directory // unless the original installation was done by Bill Weadock's // all-in-one installer for Windows. // Get a file pointing to the CTP directory. // This might be the current directory, or // it might be the CTP child. File dir; if (directory.getName().equals("RSNA")) dir = directory; else dir = new File(directory, "CTP"); // If CTP.jar exists in this directory, it is a really // old CTP main file - not used anymore File ctp = new File(dir, "CTP.jar"); if (ctp.exists()) ctp.delete(); // These are old names for the Launcher.jar file File launcher = new File(dir, "CTP-launcher.jar"); if (launcher.exists()) launcher.delete(); launcher = new File(dir, "TFS-launcher.jar"); if (launcher.exists()) launcher.delete(); // Delete the obsolete CTP-runner.jar file File runner = new File(dir, "CTP-runner.jar"); if (runner.exists()) runner.delete(); // Delete the obsolete MIRC-copier.jar file File copier = new File(dir, "MIRC-copier.jar"); if (copier.exists()) copier.delete(); // Rename the old versions of the properties files File oldprops = new File(dir, "CTP-startup.properties"); File newprops = new File(dir, "CTP-launcher.properties"); File correctprops = new File(dir, "Launcher.properties"); if (oldprops.exists()) { if (newprops.exists() || correctprops.exists()) oldprops.delete(); else oldprops.renameTo(correctprops); } if (newprops.exists()) { if (correctprops.exists()) newprops.delete(); else newprops.renameTo(correctprops); } // Get rid of obsolete startup and shutdown programs File startup = new File(dir, "CTP-startup.jar"); if (startup.exists()) startup.delete(); File shutdown = new File(dir, "CTP-shutdown.jar"); if (shutdown.exists()) shutdown.delete(); // Get rid of the obsolete linux directory File linux = new File(dir, "linux"); if (linux.exists()) { startup = new File(linux, "CTP-startup.jar"); if (startup.exists()) startup.delete(); shutdown = new File(linux, "CTP-shutdown.jar"); if (shutdown.exists()) shutdown.delete(); linux.delete(); } // clean up the libraries directory File libraries = new File(dir, "libraries"); if (libraries.exists()) { // remove obsolete versions of the slf4j libraries // and the dcm4che-imageio libraries File[] files = libraries.listFiles(); for (File file : files) { if (file.isFile()) { String name = file.getName(); if (name.startsWith("slf4j-") || name.startsWith("dcm4che-imageio-rle")) { file.delete(); } } } // remove the email subdirectory File email = new File(libraries, "email"); deleteAll(email); // remove the xml subdirectory File xml = new File(libraries, "xml"); deleteAll(xml); // remove the sftp subdirectory File sftp = new File(libraries, "sftp"); deleteAll(xml); // move edtftpj.jar to the ftp directory File edtftpj = new File(libraries, "edtftpj.jar"); if (edtftpj.exists()) { File ftp = new File(libraries, "ftp"); ftp.mkdirs(); File ftpedtftpj = new File(ftp, "edtftpj.jar"); edtftpj.renameTo(ftpedtftpj); } } // remove the obsolete xml library under dir File xml = new File(dir, "xml"); deleteAll(xml); // remove the dicom profiles so any // obsolete files will disappear File profiles = new File(dir, "profiles"); File dicom = new File(profiles, "dicom"); deleteAll(dicom); dicom.mkdirs(); // Remove the index.html file so it will be rebuilt from // example-index.html when the system next starts. File root = new File(dir, "ROOT"); if (root.exists()) { File index = new File(root, "index.html"); index.delete(); } }