List of usage examples for java.nio.file StandardCopyOption REPLACE_EXISTING
StandardCopyOption REPLACE_EXISTING
To view the source code for java.nio.file StandardCopyOption REPLACE_EXISTING.
Click Source Link
From source file:org.tinymediamanager.core.Utils.java
/** * modified version of commons-io FileUtils.moveDirectory(); adapted to Java 7 NIO<br> * since renameTo() might not work in first place, retry it up to 5 times.<br> * (better wait 5 sec for success, than always copying a 50gig directory ;)<br> * <b>And NO, we're NOT doing a copy+delete as fallback!</b> * /*from w w w.ja va 2 s . com*/ * @param srcDir * the directory to be moved * @param destDir * the destination directory * @return true, if successful * @throws IOException * if an IO error occurs moving the file */ public static boolean moveDirectorySafe(Path srcDir, Path destDir) throws IOException { // rip-off from // http://svn.apache.org/repos/asf/commons/proper/io/trunk/src/main/java/org/apache/commons/io/FileUtils.java if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.toAbsolutePath().toString().equals(destDir.toAbsolutePath().toString())) { LOGGER.debug("try to move folder " + srcDir + " to " + destDir); if (!Files.isDirectory(srcDir)) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist, or is not a directory"); } if (Files.exists(destDir) && !Files.isSameFile(destDir, srcDir)) { // extra check for Windows/OSX, where the File.equals is case insensitive // so we know now, that the Dir is the same, but the absolute name does not match throw new FileExistsException("Destination '" + destDir + "' already exists"); } if (!Files.exists(destDir.getParent())) { // create parent folder structure, else renameTo does not work try { Files.createDirectories(destDir.getParent()); } catch (Exception e) { LOGGER.error("could not create directory structure " + destDir.getParent()); // but we try a move anyway... } } // rename folder; try 5 times and wait a sec boolean rename = false; for (int i = 0; i < 5; i++) { try { // need atomic fs move for changing cASE Files.move(srcDir, destDir, StandardCopyOption.ATOMIC_MOVE); rename = true;// no exception } catch (AtomicMoveNotSupportedException a) { // if it fails (b/c not on same file system) use that try { Files.move(srcDir, destDir, StandardCopyOption.REPLACE_EXISTING); rename = true; // no exception } catch (IOException e) { } } catch (IOException e) { } if (rename) { break; // ok it worked, step out } try { LOGGER.debug("rename did not work - sleep a while and try again..."); Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.warn("I'm so excited - could not sleep"); } } // ok, we tried it 5 times - it still seems to be locked somehow. Continue // with copying as fallback // NOOO - we don't like to have some files copied and some not. if (!rename) { LOGGER.error("Failed to rename directory '" + srcDir + " to " + destDir); LOGGER.error("Movie renaming aborted."); MessageManager.instance .pushMessage(new Message(MessageLevel.ERROR, srcDir, "message.renamer.failedrename")); return false; } else { LOGGER.info("Successfully moved folder " + srcDir + " to " + destDir); return true; } } return true; // dir are equal }
From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java
private static void atomicMoveIfPossible(Path source, Path target) throws IOException { try {//from ww w. j a v a 2 s . c om Files.move(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException e) { Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); } }
From source file:org.pentaho.marketplace.domain.services.BaPluginService.java
private void writeResourceToFolder(URL resourceUrl, Path destinationFolder) { try {// w w w. j av a2 s . co m InputStream inputStream = resourceUrl.openConnection().getInputStream(); String fileName = FilenameUtils.getName(resourceUrl.toString()); Path destinationFile = destinationFolder.resolve(fileName); Files.copy(inputStream, destinationFile, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { this.getLogger().error( "Error copying " + resourceUrl.toString() + " to destination folder " + destinationFolder, e); } }
From source file:org.roda.core.RodaCoreFactory.java
private static void copyFilesFromClasspath(String classpathPrefix, Path destinationDirectory, boolean removeClasspathPrefixFromFinalPath, List<String> excludePaths) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(classpathPrefix))) .setScanners(new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[] {})))); Set<String> resources = reflections.getResources(Pattern.compile(".*")); LOGGER.info(/*from w w w .java2 s.c o m*/ "Copy files from classpath prefix={}, destination={}, removePrefix={}, excludePaths={}, #resources={}", classpathPrefix, destinationDirectory, removeClasspathPrefixFromFinalPath, excludePaths, resources.size()); for (String resource : resources) { boolean exclude = false; for (String excludePath : excludePaths) { if (resource.startsWith(excludePath)) { exclude = true; break; } } if (exclude) { continue; } InputStream originStream = RodaCoreFactory.class.getClassLoader().getResourceAsStream(resource); Path destinyPath; String resourceFileName = resource; // Removing ":" escape resourceFileName = resourceFileName.replace("::", ":"); if (removeClasspathPrefixFromFinalPath) { destinyPath = destinationDirectory.resolve(resourceFileName.replaceFirst(classpathPrefix, "")); } else { destinyPath = destinationDirectory.resolve(resourceFileName); } try { // create all parent directories Files.createDirectories(destinyPath.getParent()); // copy file Files.copy(originStream, destinyPath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { LOGGER.error("Error copying file from classpath: {} to {} (reason: {})", originStream, destinyPath, e.getMessage()); instantiatedWithoutErrors = false; } finally { RodaUtils.closeQuietly(originStream); } } }
From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java
public static void downloadAndInstall(String url, String archiveFileName, Path installPath, IProgressMonitor monitor) throws IOException { Exception error = null;//from ww w . j av a 2s.c om for (int retries = 3; retries > 0 && !monitor.isCanceled(); --retries) { try { URL dl = new URL(url); Path dlDir = ArduinoPreferences.getArduinoHome().resolve("downloads"); //$NON-NLS-1$ Files.createDirectories(dlDir); Path archivePath = dlDir.resolve(archiveFileName); URLConnection conn = dl.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); Files.copy(conn.getInputStream(), archivePath, StandardCopyOption.REPLACE_EXISTING); boolean isWin = Platform.getOS().equals(Platform.OS_WIN32); // extract ArchiveInputStream archiveIn = null; try { String compressor = null; String archiver = null; if (archiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$ compressor = CompressorStreamFactory.BZIP2; archiver = ArchiveStreamFactory.TAR; } else if (archiveFileName.endsWith(".tar.gz") || archiveFileName.endsWith(".tgz")) { //$NON-NLS-1$ //$NON-NLS-2$ compressor = CompressorStreamFactory.GZIP; archiver = ArchiveStreamFactory.TAR; } else if (archiveFileName.endsWith(".tar.xz")) { //$NON-NLS-1$ compressor = CompressorStreamFactory.XZ; archiver = ArchiveStreamFactory.TAR; } else if (archiveFileName.endsWith(".zip")) { //$NON-NLS-1$ archiver = ArchiveStreamFactory.ZIP; } InputStream in = new BufferedInputStream(new FileInputStream(archivePath.toFile())); if (compressor != null) { in = new CompressorStreamFactory().createCompressorInputStream(compressor, in); } archiveIn = new ArchiveStreamFactory().createArchiveInputStream(archiver, in); for (ArchiveEntry entry = archiveIn.getNextEntry(); entry != null; entry = archiveIn .getNextEntry()) { if (entry.isDirectory()) { continue; } // Magic file for git tarballs Path path = Paths.get(entry.getName()); if (path.endsWith("pax_global_header")) { //$NON-NLS-1$ continue; } // Strip the first directory of the path Path entryPath; switch (path.getName(0).toString()) { case "i586": case "i686": // Cheat for Intel entryPath = installPath.resolve(path); break; default: entryPath = installPath.resolve(path.subpath(1, path.getNameCount())); } Files.createDirectories(entryPath.getParent()); if (entry instanceof TarArchiveEntry) { TarArchiveEntry tarEntry = (TarArchiveEntry) entry; if (tarEntry.isLink()) { Path linkPath = Paths.get(tarEntry.getLinkName()); linkPath = installPath.resolve(linkPath.subpath(1, linkPath.getNameCount())); Files.deleteIfExists(entryPath); Files.createSymbolicLink(entryPath, entryPath.getParent().relativize(linkPath)); } else if (tarEntry.isSymbolicLink()) { Path linkPath = Paths.get(tarEntry.getLinkName()); Files.deleteIfExists(entryPath); Files.createSymbolicLink(entryPath, linkPath); } else { Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING); } if (!isWin && !tarEntry.isSymbolicLink()) { int mode = tarEntry.getMode(); Files.setPosixFilePermissions(entryPath, toPerms(mode)); } } else { Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING); } } } finally { if (archiveIn != null) { archiveIn.close(); } } return; } catch (IOException | CompressorException | ArchiveException e) { error = e; // retry } } // out of retries if (error instanceof IOException) { throw (IOException) error; } else { throw new IOException(error); } }
From source file:org.deeplearning4j.nn.modelimport.keras.e2e.KerasModelEndToEndTest.java
private MultiLayerNetwork importSequentialModelH5Test(String modelPath, int[] inputShape) throws Exception { ClassPathResource modelResource = new ClassPathResource(modelPath, KerasModelEndToEndTest.class.getClassLoader()); File modelFile = createTempFile(TEMP_MODEL_FILENAME, H5_EXTENSION); Files.copy(modelResource.getInputStream(), modelFile.toPath(), StandardCopyOption.REPLACE_EXISTING); KerasModelBuilder builder = new KerasModel().modelBuilder().modelHdf5Filename(modelFile.getAbsolutePath()) .enforceTrainingConfig(false); if (inputShape != null) { builder.inputShape(inputShape);/*from w w w . jav a2 s . co m*/ } KerasSequentialModel model = builder.buildSequential(); return model.getMultiLayerNetwork(); }
From source file:org.apache.drill.yarn.scripts.ScriptUtils.java
public void copyFile(File source, File dest) throws IOException { Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING); }
From source file:org.roda.core.storage.fs.FileStorageService.java
@Override public void revertBinaryVersion(StoragePath storagePath, String version) throws NotFoundException, RequestNotValidException, GenericException { Path binPath = FSUtils.getEntityPath(basePath, storagePath); Path binVersionPath = FSUtils.getEntityPath(historyDataPath, storagePath, version); if (!FSUtils.exists(binPath)) { throw new NotFoundException("Binary does not exist: " + binPath); }//from w w w. jav a 2 s . com if (!FSUtils.isFile(binPath)) { throw new RequestNotValidException("Not a regular file: " + binPath); } if (!FSUtils.exists(binVersionPath)) { throw new NotFoundException("Binary version does not exist: " + binVersionPath); } try { // writing file Files.copy(binVersionPath, binPath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new GenericException("Could not create binary", e); } }
From source file:org.mycore.common.MCRUtils.java
/** * Extracts files in a tar archive. Currently works only on uncompressed tar files. * /*from ww w . j a va 2 s . c om*/ * @param source * the uncompressed tar to extract * @param expandToDirectory * the directory to extract the tar file to * @throws IOException * if the source file does not exists */ public static void untar(Path source, Path expandToDirectory) throws IOException { try (TarArchiveInputStream tain = new TarArchiveInputStream(Files.newInputStream(source))) { TarArchiveEntry tarEntry; FileSystem targetFS = expandToDirectory.getFileSystem(); HashMap<Path, FileTime> directoryTimes = new HashMap<>(); while ((tarEntry = tain.getNextTarEntry()) != null) { Path target = MCRPathUtils.getPath(targetFS, tarEntry.getName()); Path absoluteTarget = expandToDirectory.resolve(target).normalize().toAbsolutePath(); if (tarEntry.isDirectory()) { Files.createDirectories(expandToDirectory.resolve(absoluteTarget)); directoryTimes.put(absoluteTarget, FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime())); } else { if (Files.notExists(absoluteTarget.getParent())) { Files.createDirectories(absoluteTarget.getParent()); } Files.copy(tain, absoluteTarget, StandardCopyOption.REPLACE_EXISTING); Files.setLastModifiedTime(absoluteTarget, FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime())); } } //restore directory dates Files.walkFileTree(expandToDirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Path absolutePath = dir.normalize().toAbsolutePath(); Files.setLastModifiedTime(absolutePath, directoryTimes.get(absolutePath)); return super.postVisitDirectory(dir, exc); } }); } }
From source file:org.deeplearning4j.nn.modelimport.keras.e2e.KerasModelEndToEndTest.java
public void importEndModelTest(String modelPath, String inputsOutputsPath, boolean tfOrdering, boolean checkPredictions, boolean checkGradients) throws Exception { ClassPathResource modelResource = new ClassPathResource(modelPath, KerasModelEndToEndTest.class.getClassLoader()); File modelFile = createTempFile(TEMP_MODEL_FILENAME, H5_EXTENSION); Files.copy(modelResource.getInputStream(), modelFile.toPath(), StandardCopyOption.REPLACE_EXISTING); KerasSequentialModel kerasModel = new KerasModel().modelBuilder() .modelHdf5Filename(modelFile.getAbsolutePath()).enforceTrainingConfig(false).buildSequential(); MultiLayerNetwork model = kerasModel.getMultiLayerNetwork(); ClassPathResource outputsResource = new ClassPathResource(inputsOutputsPath, KerasModelEndToEndTest.class.getClassLoader()); File outputsFile = createTempFile(TEMP_OUTPUTS_FILENAME, H5_EXTENSION); Files.copy(outputsResource.getInputStream(), outputsFile.toPath(), StandardCopyOption.REPLACE_EXISTING); try (Hdf5Archive outputsArchive = new Hdf5Archive(outputsFile.getAbsolutePath())) { if (checkPredictions) { INDArray input = getInputs(outputsArchive, tfOrdering)[0]; Map<String, INDArray> activationsKeras = getActivations(outputsArchive, tfOrdering); for (int i = 0; i < model.getLayers().length; i++) { String layerName = model.getLayerNames().get(i); if (activationsKeras.containsKey(layerName)) { INDArray activationsDl4j = model.feedForwardToLayer(i, input, false).get(i + 1); if (activationsDl4j.shape().length == 3) activationsDl4j = activationsDl4j.permute(0, 2, 1); compareINDArrays(layerName, activationsKeras.get(layerName), activationsDl4j, EPS); }/* w ww . ja va 2s . c o m*/ } INDArray predictionsKeras = getPredictions(outputsArchive, tfOrdering)[0]; INDArray predictionsDl4j = model.output(input, false); compareINDArrays("predictions", predictionsKeras, predictionsDl4j, EPS); INDArray outputs = getOutputs(outputsArchive, true)[0]; if (outputs.shape()[0] == 1) { outputs = outputs.reshape(outputs.shape()[1], outputs.shape()[0]); } // FIXME: int cast val nOut = (int) outputs.shape()[outputs.shape().length - 1]; compareMulticlassAUC("predictions", outputs, predictionsKeras, predictionsDl4j, nOut, EPS); } if (checkGradients && !SKIP_GRAD_CHECKS) { Random r = new Random(12345); INDArray input = getInputs(outputsArchive, tfOrdering)[0]; INDArray predictionsDl4j = model.output(input, false); //Infer one-hot labels... this probably won't work for all INDArray testLabels = Nd4j.create(predictionsDl4j.shape()); if (testLabels.rank() == 2) { for (int i = 0; i < testLabels.size(0); i++) { // FIXME: int cast testLabels.putScalar(i, r.nextInt((int) testLabels.size(1)), 1.0); } } else if (testLabels.rank() == 3) { for (int i = 0; i < testLabels.size(0); i++) { for (int j = 0; j < testLabels.size(1); j++) { // FIXME: int cast testLabels.putScalar(i, j, r.nextInt((int) testLabels.size(1)), 1.0); } } } else { throw new RuntimeException("Cannot gradient check 4d output array"); } checkGradients(model, input, testLabels); } } }