List of usage examples for org.apache.commons.io FileUtils moveFile
public static void moveFile(File srcFile, File destFile) throws IOException
From source file:fm.last.commons.io.LastFileUtils.java
/** * Moves a file "safely" - first copies it to the destination with ".part" appended to the filename, and then renames * it. This is useful for copying files to locations where files with certain extensions are processed. The rename * step should be a lot quicker than the copying step, preventing the file from being processed before it is fully * copied./*w w w . ja v a 2s .c o m*/ * * @param srcFile Source file. * @param destFile Destination file. * @throws IOException If an error occurrs moving the file. */ public static void moveFileSafely(File srcFile, File destFile) throws IOException { File partFile = new File(destFile.getParentFile(), destFile.getName() + ".part"); FileUtils.moveFile(srcFile, partFile); if (!partFile.renameTo(destFile)) { throw new IOException( "Error renaming " + partFile.getAbsolutePath() + " to " + destFile.getAbsolutePath()); } }
From source file:edu.cornell.med.icb.goby.alignments.UpgradeTo1_9_6.java
private void writeIndex(String basename, LongArrayList indexOffsets, LongArrayList indexAbsolutePositions) throws IOException { GZIPOutputStream indexOutput = null; try {/*from w ww . j a va 2s .c om*/ FileUtils.moveFile(new File(basename + ".index"), new File(makeBackFilename(basename + ".index", ".bak"))); indexOutput = new GZIPOutputStream(new FileOutputStream(basename + ".index")); final Alignments.AlignmentIndex.Builder indexBuilder = Alignments.AlignmentIndex.newBuilder(); assert (indexOffsets.size() == indexAbsolutePositions.size()) : "index sizes must be consistent."; indexBuilder.addAllOffsets(indexOffsets); indexBuilder.addAllAbsolutePositions(indexAbsolutePositions); indexBuilder.build().writeTo(indexOutput); } finally { if (indexOutput != null) indexOutput.close(); } }
From source file:de.egore911.versioning.deployer.performer.PerformCopy.java
private boolean copy(String uri, String target, String targetFilename) { URL url;//from w w w . j a v a 2s. co m try { url = new URL(uri); } catch (MalformedURLException e) { LOG.error("Invalid URI: {}", e.getMessage(), e); return false; } try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); int lastSlash = uri.lastIndexOf('/'); if (lastSlash < 0) { LOG.error("Invalid URI: {}", uri); return false; } int lastDot = uri.lastIndexOf('.'); if (lastDot < 0) { LOG.error("Invalid URI: {}", uri); return false; } String filename; if (StringUtils.isEmpty(targetFilename)) { filename = uri.substring(lastSlash + 1); } else { filename = targetFilename; } XmlHolder xmlHolder = XmlHolder.getInstance(); XPathExpression finalNameXpath = xmlHolder.xPath.compile("/project/build/finalName/text()"); if (response == HttpURLConnection.HTTP_OK) { String downloadFilename = UrlUtil.concatenateUrlWithSlashes(target, filename); File downloadFile = new File(downloadFilename); FileUtils.forceMkdir(downloadFile.getParentFile()); try (InputStream in = connection.getInputStream(); FileOutputStream out = new FileOutputStream(downloadFilename)) { IOUtils.copy(in, out); } LOG.debug("Downloaded {} to {}", url, downloadFilename); if (StringUtils.isEmpty(targetFilename)) { // Check if finalName if exists in pom.xml String destFile = null; try (ZipFile zipFile = new ZipFile(downloadFilename)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().endsWith("/pom.xml")) { String finalNameInPom; try (InputStream inputStream = zipFile.getInputStream(entry)) { try { MavenXpp3Reader mavenreader = new MavenXpp3Reader(); Model model = mavenreader.read(inputStream); finalNameInPom = model.getBuild().getFinalName(); } catch (Exception e) { Document doc = xmlHolder.documentBuilder.parse(inputStream); finalNameInPom = (String) finalNameXpath.evaluate(doc, XPathConstants.STRING); } } if (StringUtils.isNotEmpty(finalNameInPom)) { destFile = UrlUtil.concatenateUrlWithSlashes(target, finalNameInPom + "." + uri.substring(lastDot + 1)); } break; } } } // Move file to finalName if existed in pom.xml if (destFile != null) { try { File dest = new File(destFile); if (dest.exists()) { FileUtils.forceDelete(dest); } FileUtils.moveFile(downloadFile.getAbsoluteFile(), dest.getAbsoluteFile()); LOG.debug("Moved file from {} to {}", downloadFilename, destFile); } catch (IOException e) { LOG.error("Failed to move file to it's final name: {}", e.getMessage(), e); } } } return true; } else { LOG.error("Could not download file: {}", uri); return false; } } catch (SAXException | IOException | XPathExpressionException e) { LOG.error("Could not download file ({}): {}", uri, e.getMessage(), e); return false; } }
From source file:eu.openanalytics.rsb.component.DirectoryDepositHandler.java
public void handleJob(final Message<File> message) throws IOException { final DepositDirectoryConfiguration depositDirectoryConfiguration = message.getHeaders() .get(DIRECTORY_CONFIG_HEADER_NAME, DepositDirectoryConfiguration.class); final String applicationName = depositDirectoryConfiguration.getApplicationName(); final File dataFile = message.getPayload(); final File depositRootDirectory = dataFile.getParentFile().getParentFile(); final File acceptedDirectory = new File(depositRootDirectory, Configuration.DEPOSIT_ACCEPTED_SUBDIR); final File acceptedFile = new File(acceptedDirectory, dataFile.getName()); FileUtils.deleteQuietly(acceptedFile); // in case a similar job already // exists FileUtils.moveFile(dataFile, acceptedFile); final Map<String, Serializable> meta = new HashMap<String, Serializable>(); meta.put(DEPOSIT_ROOT_DIRECTORY_META_NAME, depositRootDirectory); meta.put(ORIGINAL_FILENAME_META_NAME, dataFile.getName()); meta.put(INBOX_DIRECTORY_META_NAME, dataFile.getParent()); final MultiFilesJob job = new MultiFilesJob(Source.DIRECTORY, applicationName, getUserName(), UUID.randomUUID(), (GregorianCalendar) GregorianCalendar.getInstance(), meta); try {/*from www.j a va2 s . com*/ if (FilenameUtils.isExtension(acceptedFile.getName().toLowerCase(), "zip")) { MultiFilesJob.addZipFilesToJob(new FileInputStream(acceptedFile), job); } else { MultiFilesJob.addDataToJob(new MimetypesFileTypeMap().getContentType(acceptedFile), acceptedFile.getName(), new FileInputStream(acceptedFile), job); } final String jobConfigurationFileName = depositDirectoryConfiguration.getJobConfigurationFileName(); if (StringUtils.isNotBlank(jobConfigurationFileName)) { final File jobConfigurationFile = getJobConfigurationFile(applicationName, jobConfigurationFileName); job.addFile(Constants.MULTIPLE_FILES_JOB_CONFIGURATION, new FileInputStream(jobConfigurationFile)); } getMessageDispatcher().dispatch(job); } catch (final Exception e) { final MultiFilesResult errorResult = job.buildErrorResult(e, getMessages()); handleResult(errorResult); } }
From source file:io.fabric8.maven.generator.springboot.SpringBootGenerator.java
private void copyFilesToFatJar(List<File> libs, List<File> classes, File target) throws IOException { File tmpZip = File.createTempFile(target.getName(), null); tmpZip.delete();/*from ww w . ja v a 2 s.c o m*/ // Using Apache commons rename, because renameTo has issues across file systems FileUtils.moveFile(target, tmpZip); byte[] buffer = new byte[8192]; ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip)); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target)); for (ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry()) { if (matchesFatJarEntry(libs, ze.getName(), true) || matchesFatJarEntry(classes, ze.getName(), false)) { continue; } out.putNextEntry(ze); for (int read = zin.read(buffer); read > -1; read = zin.read(buffer)) { out.write(buffer, 0, read); } out.closeEntry(); } for (File lib : libs) { try (InputStream in = new FileInputStream(lib)) { out.putNextEntry(createZipEntry(lib, getFatJarFullPath(lib, true))); for (int read = in.read(buffer); read > -1; read = in.read(buffer)) { out.write(buffer, 0, read); } out.closeEntry(); } } for (File cls : classes) { try (InputStream in = new FileInputStream(cls)) { out.putNextEntry(createZipEntry(cls, getFatJarFullPath(cls, false))); for (int read = in.read(buffer); read > -1; read = in.read(buffer)) { out.write(buffer, 0, read); } out.closeEntry(); } } out.close(); tmpZip.delete(); }
From source file:gov.nih.nci.caintegrator.file.FileManagerImpl.java
/** * {@inheritDoc}// w w w .j a va 2s .c o m */ public ResultsZipFile createInputZipFile(StudySubscription studySubscription, AbstractPersistedAnalysisJob job, String filename, File... files) { try { File inputParametersFile = createNewStudySubscriptionFile(studySubscription, "inputParameters_" + System.currentTimeMillis() + ".txt"); job.writeJobDescriptionToFile(inputParametersFile); Set<File> fileSet = new HashSet<File>(Arrays.asList(files)); fileSet.add(inputParametersFile); File tmpZipFile = new File(ZipUtils.writeZipFile(fileSet)); ResultsZipFile inputZipFile = new ResultsZipFile(); inputZipFile.setPath(createNewStudySubscriptionFile(studySubscription, filename).getAbsolutePath()); FileUtils.moveFile(tmpZipFile, inputZipFile.getFile()); inputParametersFile.delete(); return inputZipFile; } catch (IOException e) { throw new IllegalArgumentException("Couldn't create the input zip file.", e); } }
From source file:com.ikanow.infinit.e.harvest.extraction.document.file.InfiniteFile.java
public void rename(String newPathName) throws IOException { if (null != _smbFile) { try {// w w w .ja v a 2 s . c o m if (null != _auth) { _smbFile.renameTo(new SmbFile(newPathName, _auth)); } else { _smbFile.renameTo(new SmbFile(newPathName)); } } catch (SmbException e) { throw new IOException(e.getMessage()); } } //TESTED (2a.5.*, 2b.5.* - various success and fail) else if (null != _localFile) { InfiniteFile toRename = InfiniteFile.create(newPathName); File dest = toRename._localFile; if (!dest.getParentFile().exists()) { throw new IOException("Rename failed: parent directory doesn't exist"); } FileUtils.moveFile(_localFile, dest); } //TESTED (1a.5.*, 1b.5.* - various success and fail) else { throw new IOException("Operation (rename) not supported"); } //TESTED (InternalInfiniteFile, 7.9) }
From source file:com.seleniumtests.ut.reporter.TestTestStep.java
@Test(groups = { "ut" }) public void testSnapshotRenamingWithSubFolder() throws IOException { TestStep step = new TestStep("step1", null, new ArrayList<>()); ScreenShot screenshot = new ScreenShot(); File tmpImgFile = File.createTempFile("img", ".png"); File tmpImgFile2 = Paths.get(tmpImgFile.getParent(), "screenshots", tmpImgFile.getName()).toFile(); FileUtils.moveFile(tmpImgFile, tmpImgFile2); File tmpHtmlFile = File.createTempFile("html", ".html"); File tmpHtmlFile2 = Paths.get(tmpHtmlFile.getParent(), "htmls", tmpHtmlFile.getName()).toFile(); FileUtils.moveFile(tmpHtmlFile, tmpHtmlFile2); screenshot.setOutputDirectory(tmpImgFile.getParent()); screenshot.setLocation("http://mysite.com"); screenshot.setTitle("mysite"); screenshot.setImagePath("screenshots/" + tmpImgFile2.getName()); screenshot.setHtmlSourcePath("htmls/" + tmpHtmlFile2.getName()); step.addSnapshot(new Snapshot(screenshot), 0, null); Assert.assertEquals(step.getSnapshots().get(0).getScreenshot().getImagePath(), "screenshots/N-A_0-1_step1-" + tmpImgFile2.getName()); Assert.assertEquals(step.getSnapshots().get(0).getScreenshot().getHtmlSourcePath(), "htmls/N-A_0-1_step1-" + tmpHtmlFile2.getName()); }
From source file:com.fusesource.example.camel.ingest.FileIngestorRouteBuilderTest.java
protected void createAndMoveFile(AggregateRecordType agt) throws Exception { File testFile = new File("./target/test.xml"); if (testFile.exists()) { testFile.delete();//from w w w. j a v a2 s .c om } ObjectFactory objFact = new ObjectFactory(); JAXBContext context = JAXBContext.newInstance(ObjectFactory.class); Marshaller m = context.createMarshaller(); m.marshal(objFact.createAggregateRecord(agt), testFile); // not really atomic, but it works for tests FileUtils.moveFile(testFile, new File(pollingFolder, "test.xml")); }
From source file:gov.nih.nci.caintegrator.application.analysis.grid.preprocess.PreprocessDatasetGridRunner.java
private File replaceGctFileWithPreprocessed(File gctFile, File zipFile) throws IOException { File zipFileDirectory = new File(zipFile.getParent().concat("/tempPreprocessedZipDir")); FileUtils.deleteDirectory(zipFileDirectory); FileUtils.forceMkdir(zipFileDirectory); FileUtils.waitFor(zipFileDirectory, TIMEOUT_SECONDS); Cai2Util.isValidZipFile(zipFile); ZipUtilities.unzip(zipFile, zipFileDirectory); FileUtils.waitFor(zipFileDirectory, TIMEOUT_SECONDS); Cai2Util.printDirContents(zipFileDirectory); if (zipFileDirectory.list() != null) { if (zipFileDirectory.list().length != 1) { int dirListlength = zipFileDirectory.list().length; FileUtils.deleteDirectory(zipFileDirectory); throw new IllegalStateException("The zip file returned from PreprocessDataset" + " should have exactly 1 file instead of " + dirListlength); }/* ww w .jav a 2s . c om*/ } else { String zipFileDirectoryPath = zipFileDirectory.getAbsolutePath(); FileUtils.deleteDirectory(zipFileDirectory); throw new IllegalStateException( "The zip file directory list at path: " + zipFileDirectoryPath + "is null."); } String[] files = zipFileDirectory.list(); File preprocessedFile = new File(zipFileDirectory, files[0]); FileUtils.deleteQuietly(gctFile); // Remove the non-preprocessed file FileUtils.moveFile(preprocessedFile, gctFile); // move to gctFile FileUtils.deleteQuietly(zipFile); FileUtils.deleteDirectory(zipFileDirectory); return gctFile; }