List of usage examples for java.io File renameTo
public boolean renameTo(File dest)
From source file:com.pr7.logging.CustomDailyRollingFileAppender.java
/** * Rollover the current file to a new file. *///from w ww . j av a2 s . c o m void rollOver() throws IOException { /* Compute filename, but only if datePattern is specified */ if (datePattern == null) { errorHandler.error("Missing DatePattern option in rollOver()."); return; } String datedFilename = fileName + sdf.format(now); // It is too early to roll over because we are still within the // bounds of the current interval. Rollover will occur once the // next interval is reached. if (scheduledFilename.equals(datedFilename)) { return; } // close current file, and rename it to datedFilename this.closeFile(); File target = new File(scheduledFilename); if (target.exists()) { target.delete(); } File file = new File(fileName); boolean result = file.renameTo(target); if (result) { LogLog.debug(fileName + " -> " + scheduledFilename); } else { LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "]."); } try { // This will also close the file. This is OK since multiple // close operations are safe. this.setFile(fileName, false, this.bufferedIO, this.bufferSize); } catch (IOException e) { errorHandler.error("setFile(" + fileName + ", false) call failed."); } scheduledFilename = datedFilename; }
From source file:com.adaptris.core.fs.AggregatingFsConsumer.java
private void renameAggregatedFiles(List<AdaptrisMessage> msgs) { for (AdaptrisMessage m : msgs) { Map<?, ?> objectMetadata = m.getObjectHeaders(); if (objectMetadata.containsKey(OBJ_METADATA_KEY_FILE)) { File f = ((File) objectMetadata.get(OBJ_METADATA_KEY_FILE)); File parent = f.getParentFile(); String name = f.getName().replaceAll(wipSuffix().replaceAll("\\.", "\\\\."), ""); log.trace("Will Rename " + f.getName() + " back to " + name); File newFile = new File(parent, name); f.renameTo(newFile); }//from ww w . ja v a 2s . c om } }
From source file:com.cloud.utils.S3Utils.java
@SuppressWarnings("unchecked") public static File getFile(final ClientOptions clientOptions, final String bucketName, final String key, final File targetDirectory, final FileNamingStrategy namingStrategy) { assert clientOptions != null; assert isNotBlank(bucketName); assert isNotBlank(key); assert targetDirectory != null && targetDirectory.isDirectory(); assert namingStrategy != null; final AmazonS3 connection = acquireClient(clientOptions); File tempFile = null; try {// w w w . j a v a2 s.c om tempFile = createTempFile(join("-", targetDirectory.getName(), currentTimeMillis(), "part"), "tmp", targetDirectory); tempFile.deleteOnExit(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(format("Downloading object %1$s from bucket %2$s to temp file %3$s", key, bucketName, tempFile.getName())); } try { connection.getObject(new GetObjectRequest(bucketName, key), tempFile); } catch (AmazonClientException ex) { // hack to handle different ETAG format generated from RiakCS for multi-part uploaded object String msg = ex.getMessage(); if (!msg.contains("verify integrity")) { throw ex; } } final File targetFile = new File(targetDirectory, namingStrategy.determineFileName(key)); tempFile.renameTo(targetFile); return targetFile; } catch (FileNotFoundException e) { throw new CloudRuntimeException( format("Failed open file %1$s in order to get object %2$s from bucket %3$s.", targetDirectory.getAbsoluteFile(), bucketName, key), e); } catch (IOException e) { throw new CloudRuntimeException( format("Unable to allocate temporary file in directory %1$s to download %2$s:%3$s from S3", targetDirectory.getAbsolutePath(), bucketName, key), e); } finally { if (tempFile != null) { tempFile.delete(); } } }
From source file:com.servicelibre.jxsl.scenario.test.xspec.XspecTestScenarioRunner.java
private void addParamToGeneratedTestFile(File generatedTestFile, String encoding) { // Ajouter <xsl:param name="docUrl" required="yes"/> try {/* w w w . j a va 2 s. c o m*/ String fileString = FileUtils.readFileToString(generatedTestFile, encoding); // file:/jxslTestDocument => {$docUrl} String newContent = fileString.replaceAll(JXSL_TEST_HREF_PLACEHOLDER, "href=\"\\{\\$docUrl\\}\""); newContent = newContent.replaceAll(JXSL_TEST_SELECT_PLACEHOLDER, "doc\\(\\$docUrl\\)"); newContent = newContent.replace("</xsl:stylesheet>", "<xsl:param name=\"docUrl\" required=\"yes\"/></xsl:stylesheet>"); String generatedTestFilePath = generatedTestFile.getAbsolutePath(); File newFile = new File(generatedTestFilePath + ".new"); FileUtils.writeStringToFile(newFile, newContent, encoding); FileUtils.deleteQuietly(generatedTestFile); if (!newFile.renameTo(new File(generatedTestFilePath))) { logger.error("Error while renaming {} to {}", newFile, generatedTestFilePath); } } catch (IOException e) { logger.error("Error while replacing jxslTestDocument placeholder", e); } }
From source file:org.mulima.internal.audio.tool.ShnToolSplitter.java
/** * {@inheritDoc}/*from w w w . j ava 2 s .c o m*/ */ @Override public SplitterResult split(DiscFile source, File destDir) { String sourcePath = FileUtil.getSafeCanonicalPath(source); String destPath = FileUtil.getSafeCanonicalPath(destDir); List<String> command = new ArrayList<String>(); command.add(getPath()); command.add("split"); if (!"".equals(getOpts())) { command.add(getOpts()); } command.add("-O"); command.add(overwrite ? "always" : "never"); command.add("-d"); command.add(destPath); command.add(sourcePath); boolean track0 = true; StringWriter input = new StringWriter(); PrintWriter writer = new PrintWriter(input); for (Track track : source.getMeta().getTracks()) { String time = track.getStartPoint().getTime(); if ("00:00:00".equals(time) || "00:00.000".equals(time)) { track0 = false; } writer.println(time.replaceAll(":([^:\\.]+)$", ".$1")); } writer.close(); ProcessResult procResult = new ProcessCaller("split of " + FileUtil.getSafeCanonicalPath(source), command, input.toString()).call(); int offset = track0 ? -1 : 0; for (File file : destDir.listFiles()) { Matcher matcher = SPLIT_FILE_REGEX.matcher(file.getName()); if (matcher.find()) { int num = Integer.parseInt(matcher.group(1)) + offset; if (num == 0) { if (!file.delete()) { throw new UncheckedIOException("Could not delete track 0: " + file); } } else { if (!file.renameTo(new File(destDir, String.format("D%02dT%02d.%s", source.getDiscNum(), num, AudioFormat.WAVE.getExtension())))) { throw new UncheckedIOException("Could not rename track: " + file); } } } } CachedDir<AudioFile> dest = fileService.createCachedDir(AudioFile.class, destDir); return new SplitterResult(source, dest.getValues(TrackFile.class), procResult); }
From source file:dk.netarkivet.wayback.aggregator.AggregationWorker.java
/** * Give the FINAL_INDEX_FILE (wayback.index) a unique new name. *//* www.jav a2 s . c o m*/ private void renameFinalIndexFile() { String timestampString = (new SimpleDateFormat("yyyyMMdd-HHmm")).format(new Date()); String newFileName = "wayback." + timestampString + ".cdx"; File fileToRename = new File(indexOutputDir, FINAL_INDEX_FILE.getName()); File newFile = new File(indexOutputDir, newFileName); if (newFile.exists()) { //This should be rare outside tests newFileName = UUID.randomUUID().toString() + "." + newFileName; newFile = new File(indexOutputDir, newFileName); } fileToRename.renameTo(newFile); }
From source file:de.tudarmstadt.ukp.dkpro.core.io.web1t.Web1TFormatWriter.java
private int processInputFileForLevel(int level, Comparator<String> comparator) throws IOException { org.apache.uima.util.Logger logger = getContext().getLogger(); File unsortedInputFile = new File(outputPath, level + ".txt"); File outputFolder = getOutputFolder(level); outputFolder.mkdir();//from w ww . j a va 2s.c om FrequencyDistribution<String> letterFD = letterFDs.get(level); Web1TFileSplitter splitter = new Web1TFileSplitter(unsortedInputFile, outputFolder, outputEncoding, letterFD, splitThreshold, 0, logger); splitter.split(); LinkedList<File> splitFiles = splitter.getFiles(); Web1TFileSorter sorter = new Web1TFileSorter(splitFiles, comparator, logger); sorter.sort(); splitter.cleanUp(); // Remove files from previous step LinkedList<File> sortedFiles = sorter.getSortedFiles(); Web1TFileConsolidator consolidator = new Web1TFileConsolidator(sortedFiles, comparator, outputEncoding, minFreq, logger); 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:net.sourceforge.cobertura.util.FileFinder2Test.java
@Test public void testSearchJarsForSourceInJar() throws IOException { File tempDir = TestUtils.getTempDir(); File zipFile = TestUtils.createSourceArchive(tempDir); //now test the FileFinder FileFinder fileFinder = new FileFinder(); fileFinder.addSourceDirectory(zipFile.getParentFile().getAbsolutePath()); Source source = fileFinder.getSource(TestUtils.SIMPLE_SOURCE_PATHNAME); verifySource(source);/*from w w w.ja va2s. co m*/ /* * Now make sure jar files are used. Rename the zip file to be a jar file */ File jarFile = new File(zipFile.getParentFile(), "source.jar"); assertTrue(zipFile.renameTo(jarFile)); fileFinder = new FileFinder(); fileFinder.addSourceDirectory(zipFile.getParentFile().getAbsolutePath()); source = fileFinder.getSource(TestUtils.SIMPLE_SOURCE_PATHNAME); verifySource(source); }
From source file:com.facebook.samples.musicdashboard.MusicFetcher.java
void downloadUrlToFilePath(String urlSpec, File file) throws IOException { URL url = new URL(urlSpec); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); FileOutputStream out = null;/*from w w w .ja va 2 s .c o m*/ try { File tempFile = File.createTempFile("download", ".jpg", file.getParentFile()); out = new FileOutputStream(tempFile); InputStream in = connection.getInputStream(); int bytesRead = 0; byte[] buffer = new byte[1024]; while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } out.close(); out = null; tempFile.renameTo(file); } finally { connection.disconnect(); if (out != null) out.close(); } }
From source file:de.tudarmstadt.ukp.dkpro.core.io.web1t.Web1TFormatWriter.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 ww .j a v a 2 s . com * @throws IOException */ private void processCreatedMiscFileAgain(int level, Comparator<String> comparator, int nextFileNumber) throws IOException { org.apache.uima.util.Logger logger = getContext().getLogger(); 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, logger); splitter.split(); LinkedList<File> splittedFiles = splitter.getFiles(); Web1TFileSorter sorter = new Web1TFileSorter(splittedFiles, comparator, logger); sorter.sort(); LinkedList<File> sortedFiles = splitter.getFiles(); splitThreshold = oldThreshold; misc.delete(); Web1TFileConsolidator consolidator = new Web1TFileConsolidator(sortedFiles, comparator, outputEncoding, minFreq, logger); 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(); }