/** * Write the dex program resources and proguard resource to @code{directory}. */ public void writeToDirectory(Path directory, OutputMode outputMode) throws IOException { if (outputMode == OutputMode.Indexed) { for (Path path : Files.list(directory).collect(Collectors.toList())) { if (isClassesDexFile(path)) { Files.delete(path); } } } CopyOption[] options = new CopyOption[] {StandardCopyOption.REPLACE_EXISTING}; try (Closer closer = Closer.create()) { List<Resource> dexProgramSources = getDexProgramResources(); for (int i = 0; i < dexProgramSources.size(); i++) { Path filePath = directory.resolve(outputMode.getOutputPath(dexProgramSources.get(i), i)); if (!Files.exists(filePath.getParent())) { Files.createDirectories(filePath.getParent()); } Files.copy(closer.register(dexProgramSources.get(i).getStream()), filePath, options); } } }
@Override public Map<CloudPath,CloudMethod> copy(BlobStoreContext context, Set<CloudPath> sources, Path target, Set<CopyOption> options) throws IOException { boolean copyMethodReturns = !options.contains(CloudCopyOption.DONT_RETURN_COPY_METHOD); Map<CloudPath,CloudMethod> copyMethodsMap = copyMethodReturns ? new HashMap<>() : null; for (CloudPath source : sources) { try { copy(context, source, target, options); } catch (IOException e) { if (options.contains(CloudCopyOption.FAIL_SILENTLY)) { LOG.warn("Copy from {} to {} failed, slient failure specified, continuing", source, target, e); } else { throw e; } } } return copyMethodsMap; }
protected CloudMethod determineCloudMethodForCopyOrMoveOperations( String operationName, CloudPath source, Path target, Set<CopyOption> options) throws IOException { // Don't copy a file to itself if (source.equals(target)) { throw new FileAlreadyExistsException("Cannot " + operationName + " a path to itself from '" + source.toAbsolutePath() + "' -> '" + target.toAbsolutePath() + "'"); } // Check if target exists and we are allowed to copy if (Files.exists(target) && !options.contains(StandardCopyOption.REPLACE_EXISTING)) { throw new FileAlreadyExistsException("Cannot copy from " + source.toAbsolutePath() + " to " + target.toAbsolutePath() + ", the file already exists and file replace was not specified"); } // Check if we can try a JClouds copy or we have to use the filesystem if (target instanceof CloudPath) { // Work out if we are using the same cloud settings - if we are then we can use a direct copy CloudPath cloudPathTarget = (CloudPath)target; if (source.getFileSystem().getCloudHostConfiguration().canOptimiseOperationsFor(cloudPathTarget)) { return CloudMethod.CLOUD_OPTIMISED; } } return CloudMethod.LOCAL_FILESYSTEM_FALLBACK; }
@Override public void move(Path source, Path target, CopyOption... options) throws IOException { HashSet<CopyOption> copyOptions = Sets.newHashSet(options); if (copyOptions.contains(StandardCopyOption.ATOMIC_MOVE)) { throw new AtomicMoveNotSupportedException(source.toString(), target.toString(), "ATOMIC_MOVE not supported yet"); } if (Files.isDirectory(source)) { MCRPath src = MCRFileSystemUtils.checkPathAbsolute(source); MCRDirectory srcRootDirectory = getRootDirectory(src); if (srcRootDirectory.hasChildren()) { throw new IOException("Directory is not empty"); } } copy(source, target, options); delete(source); }
@Override public void move(Path source, Path target, CopyOption... options) throws IOException { JPath jPath = (JPath) target; copy(source, target, options); Status status = jPath.getBfsFile().getStatus(); if (status.getType() == Status.FileType.NULL) { throw new IOException(L.l("unable to move {0} to {1}", source.toUri(), target.toUri())); } delete(source); }
public String copyRename(String origin, String destination)// method to copy // a // file from a // directory and // rename it or // change the // extension throws IOException { Path FROM = Paths.get(origin); String cnt = Integer.toString(counter); counter++; String res = destination.concat(cnt.concat(".txt")); Path TO = Paths.get(res); // overwrite the destination file if it exists, and copy // the file attributes, including the rwx permissions CopyOption[] options = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES }; Files.copy(FROM, TO, options); return res; // return a string of the path of the new txt file }
private void copyFile(Config config, Path sourcePath) throws IOException { boolean subscribe = config.getCaption(); boolean left = config.getLeft(); boolean top = config.getTop(); int fontSize = config.getFontSize(); if (!subscribe || fontSize <= 0) { Path targetPath = Paths.get(config.getDesktopFolder()+"\\"+sourcePath.getFileName().toString()); CopyOption options = StandardCopyOption.REPLACE_EXISTING; Files.copy(sourcePath, targetPath, options); } else { logger.info("write path to " + sourcePath.toString()); BufferedImage image = PictureCaption.convert(sourcePath.toString(), sourcePath.toString(), left, top, fontSize); String filename = sourcePath.getFileName().toString(); filename = filename.toLowerCase().replace("jpg", "png"); File outputfile = new File(config.getDesktopFolder()+"\\"+filename); ImageIO.write(image, "png", outputfile); } }
default boolean retrieveIfNeeded( FTPFile remote, Path target, CopyOption... options ) throws IOException { if( remote != null && target != null && isPathRetrievable( target, remote ) ) { try( InputStream is = retrieveFileStream( remote ) ) { if( is == null ) { throw new FileNotFoundException( target.toString() ); } Files.copy( is, target, options ); } finally { completePendingCommand(); } } return Files.exists( target, LinkOption.NOFOLLOW_LINKS ) && Files.isRegularFile( target, LinkOption.NOFOLLOW_LINKS ); }
public boolean extract(String srcZip, String targetPath, OnCondition listener) throws IOException { ZipFile in = new ZipFile(srcZip); Enumeration<? extends ZipEntry> entries = in.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String zipEntryPath = entry.getName(); if (listener.onCondition(zipEntryPath)) { zipEntryPath = "/" + zipEntryPath; File resFile = Paths.get(targetPath, zipEntryPath).toFile(); if (entry.isDirectory()) { if (!resFile.exists() && !resFile.mkdir()) { // Log.t(TAG, "can not make new Res Directory : " + resFile.getAbsolutePath()); return false; } } else { Files.copy(in.getInputStream(entry), resFile.toPath(), new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }); } } } in.close(); return true; }
public static void copyRecursively(final Path source, final Path destination, final CopyOption... copyOptions) throws IOException { final Set<CopyOption> copyOptionsSet = new HashSet<>( Arrays.asList(copyOptions)); if (!isDirectory(source)) throw new FileNotFoundException("Not a directory: " + source); if (isDirectory(destination) && !copyOptionsSet.contains(REPLACE_EXISTING)) throw new FileAlreadyExistsException(destination.toString()); Path destinationParent = destination.getParent(); if (destinationParent != null && !isDirectory(destinationParent)) throw new FileNotFoundException("Not a directory: " + destinationParent); RecursiveCopyFileVisitor visitor = new RecursiveCopyFileVisitor( destination, copyOptionsSet, source); Set<FileVisitOption> walkOptions = noneOf(FileVisitOption.class); if (!copyOptionsSet.contains(NOFOLLOW_LINKS)) walkOptions = EnumSet.of(FOLLOW_LINKS); walkFileTree(source, walkOptions, MAX_VALUE, visitor); }
RecursiveCopyFileVisitor(Path destination, Set<CopyOption> copyOptionsSet, Path source) { this.destination = destination; this.source = source; this.copyOptionsSet = new HashSet<>(copyOptionsSet); HashSet<Object> linkOptionsSet = new HashSet<>(); for (CopyOption option : copyOptionsSet) { copyOptionsSet.add(option); if (option instanceof LinkOption) linkOptionsSet.add((LinkOption) option); } this.linkOptions = linkOptionsSet .toArray(new LinkOption[(linkOptionsSet.size())]); this.ignoreErrors = copyOptionsSet.contains(IGNORE_ERRORS); /* * To avoid UnsupporteOperationException from native java.nio operations * we strip our own options out */ copyOptionsSet.removeAll(EnumSet.allOf(RecursiveCopyOption.class)); copyOptions = copyOptionsSet.toArray(new CopyOption[(copyOptionsSet .size())]); }
/** {@inheritDoc} */ @Override public void move(Path source, Path target, CopyOption... options) throws IOException { source = ((TestPath) source).unwrap(); target = ((TestPath) target).unwrap(); checkIfRemoved(source); Path sourceParent = source.getParent(); if (sourceParent != null) { checkIfRemoved(sourceParent); checkPermissions(sourceParent, true, AccessMode.WRITE); } Path targetParent = target.getParent(); if (targetParent != null) { checkIfRemoved(targetParent); checkPermissions(targetParent, true, AccessMode.WRITE); } provider.move(source, target, options); }
@Override public void move( Path srcpath, SecureDirectoryStream<Path> targetdir, Path targetpath) throws IOException { EphemeralFsPath efsSrcPath = cast(srcpath); EphemeralFsPath efsTargetPath = cast(targetpath); EphemeralFsSecureDirectoryStream efsTargetDir = cast(targetdir); synchronized(efsSrcPath.fs.fsLock) { EphemeralFsPath actualSrcPath = translate(efsSrcPath); EphemeralFsPath actualTargetPath = efsTargetDir.translate(efsTargetPath); efsSrcPath.fs.move(actualSrcPath, actualTargetPath, new CopyOption[] {StandardCopyOption.ATOMIC_MOVE}); } }
public void copyFile(boolean deleteSourceFile, byte[] srcPath, byte[] targetPath, CopyOption... options) throws IOException { List<CopyOption> opts = Arrays.asList(options); if (!exists(srcPath)) { throw new FileNotFoundException(); } if (exists(targetPath) && !opts.contains(StandardCopyOption.REPLACE_EXISTING)) { System.out.println("Its me"); throw new FileAlreadyExistsException(new String(targetPath)); } beginWrite(); try { TarEntry srcEntry = getTarEntryFromPath(srcPath); byte[] data = entriesToData.get(srcEntry); if (exists(targetPath)) { deleteFile(targetPath, true); } TarEntry targetEntry = new TarEntry(TarHeader.createHeader( new String(targetPath), data.length, srcEntry.getModTime() .getTime(), srcEntry.isDirectory())); addEntry(targetEntry, data); } finally { endWrite(); } }
/** * Copy source file to target location. If {@code prompt} is true then * prompt user to overwrite target if it exists. The {@code preserve} * parameter determines if file attributes should be copied/preserved. */ private static void copyFile(Path source, Path target, boolean prompt, boolean preserve) { CopyOption[] options = (preserve) ? new CopyOption[] { COPY_ATTRIBUTES, REPLACE_EXISTING } : new CopyOption[] { REPLACE_EXISTING }; try { Files.createDirectories(target.getParent()); } catch (IOException e) { e.printStackTrace(); } try { Files.copy(source, target, options); } catch (IOException x) { log.error(String.format("Unable to copy: %s: %n", source), x); } }
@Override public void move(Path srcPath, SecureDirectoryStream<Path> targetDir, Path targetPath) throws IOException { checkOpen(); JimfsPath checkedSrcPath = checkPath(srcPath); JimfsPath checkedTargetPath = checkPath(targetPath); if (!(targetDir instanceof JimfsSecureDirectoryStream)) { throw new ProviderMismatchException( "targetDir isn't a secure directory stream associated with this file system"); } JimfsSecureDirectoryStream checkedTargetDir = (JimfsSecureDirectoryStream) targetDir; view.copy( checkedSrcPath, checkedTargetDir.view, checkedTargetPath, ImmutableSet.<CopyOption>of(), true); }
/** * Copy source file to target location. * * @return */ static boolean copyFile(Path source, Path target) { CopyOption[] options = new CopyOption[] { COPY_ATTRIBUTES, REPLACE_EXISTING }; target = getUnique(target); try { Files.copy(source, target, options); return true; } catch (Exception x) { System.err.format("Unable to copy: %s: %s%n", source, x); return false; } }
static Flags fromCopyOptions(CopyOption... options) { Flags flags = new Flags(); flags.followLinks = true; for (CopyOption option: options) { if (option == StandardCopyOption.REPLACE_EXISTING) { flags.replaceExisting = true; continue; } if (option == LinkOption.NOFOLLOW_LINKS) { flags.followLinks = false; continue; } if (option == StandardCopyOption.COPY_ATTRIBUTES) { // copy all attributes but only fail if basic attributes // cannot be copied flags.copyBasicAttributes = true; flags.copyPosixAttributes = true; flags.copyNonPosixAttributes = true; flags.failIfUnableToCopyBasic = true; continue; } if (ExtendedOptions.INTERRUPTIBLE.matches(option)) { flags.interruptible = true; continue; } if (option == null) throw new NullPointerException(); throw new UnsupportedOperationException("Unsupported copy option"); } return flags; }
static Flags fromMoveOptions(CopyOption... options) { Flags flags = new Flags(); for (CopyOption option: options) { if (option == StandardCopyOption.ATOMIC_MOVE) { flags.atomicMove = true; continue; } if (option == StandardCopyOption.REPLACE_EXISTING) { flags.replaceExisting = true; continue; } if (option == LinkOption.NOFOLLOW_LINKS) { // ignore continue; } if (option == null) throw new NullPointerException(); throw new UnsupportedOperationException("Unsupported copy option"); } // a move requires that all attributes be copied but only fail if // the basic attributes cannot be copied flags.copyBasicAttributes = true; flags.copyPosixAttributes = true; flags.copyNonPosixAttributes = true; flags.failIfUnableToCopyBasic = true; return flags; }
public static void copyFileOrFolder(File source, File dest, CopyOption... options){ if(source.isDirectory()) copyFolder(source, dest, options); else { ensureParentFolder(dest); copyFile(source, dest, options); } }
private static void copyFolder(File source, File dest, CopyOption... options){ if(!dest.exists()) dest.mkdirs(); File[] contents = source.listFiles(); if(contents != null) { for(File f : contents) { File newFile = new File(dest.getAbsolutePath() + File.separator + f.getName()); if(f.isDirectory()) copyFolder(f, newFile, options); else copyFile(f, newFile, options); } } }
private static void copyFile(File source, File dest, CopyOption... options){ try { Files.copy(source.toPath(), dest.toPath(), options); } catch (IOException e) { e.printStackTrace(); } }
public static boolean renameTo( Path from, Path to, CopyOption... options ) { try { return Files.move( from, to, options ) != null; } catch( IOException e ) { return false; } }
/** * Copies the remote file from one cloud to another using the local file system. This will be used when * {@link CloudHostConfiguration#canCopyOrMoveInternally(CloudHostConfiguration)} returns false * @see #copy(BlobStoreContext, CloudPath, Path, CopyOption...) * @param context * @param source * @param target * @param options * @throws IOException * TODO: This doesn't handle directory copies only single files * TODO: Implement access checks */ protected void copyUsingLocalFilesystem(BlobStoreContext context, CloudPath source, Path target, Set<CopyOption> options) throws IOException { FileSystemProviderHelper.copyDirectoryBetweenProviders(source, target, new FileSystemProviderHelper.AcceptAllFilter(), options.contains(CloudCopyOption.RECURSIVE)); // CloudBasicFileAttributes sourceAttributes = readAttributes(context, CloudBasicFileAttributes.class, source); // if (sourceAttributes.isDirectory()) { // // } else { // LOG.info("Copying from local filesystem {} to target location {}...", source.toAbsolutePath(), target.toAbsolutePath()); // StandardOpenOption createOpt = options.contains(StandardCopyOption.REPLACE_EXISTING) ? // StandardOpenOption.CREATE : StandardOpenOption.CREATE_NEW; // LOG.debug("Opening a channel to {} with create option {}", target.toAbsolutePath(), createOpt); // // // Open the file to write // try ( SeekableByteChannel targetChannel = Files.newByteChannel(target, EnumSet.of(createOpt, StandardOpenOption.WRITE)) ) { // EnumSet<StandardOpenOption> readOptions = EnumSet.of(StandardOpenOption.READ); // LOG.debug("Opening a channel to {} with create option {}", target.toAbsolutePath(), createOpt); // // // Open the file to read // try ( CloudFileChannel sourceChannel = newByteChannel(context, source, readOptions) ) { // // Transfer // sourceChannel.transferTo(0L, sourceChannel.size(), targetChannel); // } // } // // LOG.info("Finished copying from local filesystem {} to target location {}", source.toAbsolutePath(), target.toAbsolutePath()); // } }
@Override public CloudMethod move(BlobStoreContext context, CloudPath source, Path target, Set<CopyOption> options) throws IOException { LOG.info("Performing move operation from '{}' -> '{}' using copy/delete", source, target); CloudMethod method = copy(context, source, target, options); delete(context, source, options.contains(CloudCopyOption.RECURSIVE) ? EnumSet.of(DeleteOption.RECURSIVE) : EnumSet.noneOf(DeleteOption.class)); return method; }
@Override public void copy(Path source, Path target, CopyOption... options) throws IOException { CloudPath sourceCloudPath = getCloudPath(source); Set<CopyOption> copyOptions = copyOptionsToSet(options); CloudFileSystemImplementation sourceCloudFileSystemImplementation = getCloudFileSystemImplementation(sourceCloudPath); sourceCloudFileSystemImplementation.copy(getBlobStoreContext(sourceCloudPath), sourceCloudPath, target, copyOptions); }
private void copyMultiplePaths(Path target, Set<CopyOption> copyOptions, Set<CloudPath> copyPaths) throws IOException { if (!copyPaths.isEmpty()) { CloudPath firstDegradedCloudPath = copyPaths.stream().findFirst().get(); CloudFileSystemImplementation cloudFileSystemImplementation = getCloudFileSystemImplementation(firstDegradedCloudPath); cloudFileSystemImplementation.copy(getBlobStoreContext(firstDegradedCloudPath), copyPaths, target, copyOptions); } }
@Override public void move(Path source, Path target, CopyOption... options) throws IOException { CloudPath sourceCloudPath = getCloudPath(source); Set<CopyOption> copyOptions = copyOptionsToSet(options); CloudFileSystemImplementation sourceCloudFileSystemImplementation = getCloudFileSystemImplementation(sourceCloudPath); sourceCloudFileSystemImplementation.move(getBlobStoreContext(sourceCloudPath), sourceCloudPath, target, copyOptions); }
@Test public void testCopyMultiplePathsWillPerformTwoCopiesForADegradedAndAnOptimisedCopy() throws IOException { CloudPath targetPath = context.mock(CloudPath.class, "targetPath"); CloudPath path1 = createMockCloudPathWithCanOptimiseOperationsBetween(targetPath, true); CloudPath path2 = createMockCloudPathWithCanOptimiseOperationsBetween(targetPath, false); CloudPath path3 = createMockCloudPathWithCanOptimiseOperationsBetween(targetPath, true); Set<CopyOption> originalCopyOpts = Sets.newHashSet(CloudCopyOption.FAIL_SILENTLY, CloudCopyOption.RECURSIVE); Set<CopyOption> degradedCopyOpts = Sets.newHashSet(originalCopyOpts); degradedCopyOpts.add(CloudCopyOption.DONT_RETURN_COPY_METHOD); Set<CopyOption> optimisedCopyOpts = Sets.newHashSet(degradedCopyOpts); BlobStoreContext blobStoreContext = context.mock(BlobStoreContext.class, "blobStoreContext-1"); CloudFileSystem fileSystem = context.mock(CloudFileSystem.class, "fileSystem-1"); CloudFileSystemImplementation cloudFileSystemImplementation = createGetCloudFileSystemImplementationExpectations(fileSystem, true, path1, path2, path3); context.checking(new Expectations() {{ allowing(fileSystem).getBlobStoreContext(); will(returnValue(blobStoreContext)); exactly(1).of(cloudFileSystemImplementation).copy(blobStoreContext, Sets.newHashSet(path1, path2, path3), targetPath, optimisedCopyOpts); }}); impl.copy(Sets.newHashSet(path1, path2, path3), targetPath, originalCopyOpts); }
/** * Retrieve a remote file * <p> * @param remote file name * @param target file to create. Name will also be the remote name in the current directory * @param options CopyOptions to use * <p> * @throws IOException */ default void retrieve( String remote, Path target, CopyOption... options ) throws IOException { try( InputStream is = retrieveFileStream( remote ) ) { if( is == null ) { throw new FileNotFoundException( target.toString() ); } Files.copy( is, target, options ); } finally { completePendingCommand(); } }
@Override public void move( P target, CopyOption... options ) throws IOException { if( Files.isSameFile( getFileSystem().getCachePath(), target.getFileSystem().getCachePath() ) ) { fs.getFileSystemIO().copyFile( true, getResolvedPath(), target.getResolvedPath(), options ); } else { copyToTarget( target, options ); delete(); } }
@Override public void copy( P target, CopyOption... options ) throws IOException { if( Files.isSameFile( getFileSystem().getCachePath(), target.getFileSystem().getCachePath() ) ) { fs.getFileSystemIO().copyFile( false, getResolvedPath(), target.getResolvedPath(), options ); } else { copyToTarget( target, options ); } }
@Override public void copyFile( boolean b, char[] src, char[] dest, CopyOption... options ) throws IOException { // This will retrieve source as necessary exists( src ); delegate.copyFile( b, src, dest, options ); }
@Override public final void copyFile( boolean b, char[] src, char[] dest, CopyOption... options ) throws IOException { try { Files.copy( toPath( src ), toPath( dest ), options ); } catch( FileNotFoundException ex ) { throw new FileNotFoundException( String.valueOf( src ) ); } }
@Override public void move( MemoryPath target, CopyOption... options ) throws IOException { boolean repExisting = false; for( CopyOption opt: options ) { // No need to implement StandardCopyOption.ATOMIC_MOVE as we always are & StandardCopyOption.COPY_ATTRIBUTES is unsupported if( opt == StandardCopyOption.REPLACE_EXISTING ) { repExisting = true; } } }
@Override public void move( Path source, Path target, CopyOption... options ) throws IOException { MemoryPath src = toPath( source ); MemoryPath dst = toPath( target ); if( !src.isSameFile( dst ) ) { src.move( dst, options ); } }
private void checkCopyOptions(CopyOption[] options) { for (CopyOption option : options) { if (!SUPPORTED_COPY_OPTIONS.contains(option)) { throw new UnsupportedOperationException("Unsupported copy option: " + option); } } }
@Override public void copy(Path source, Path target, CopyOption... options) throws IOException { JPath jSource = (JPath) source; JPath jTarget = (JPath) target; try (InputStream is = jSource.getBfsFile().openRead()) { if (is == null) { throw new IOException(L.l("unable to read from file {0}", source.toUri())); } ArrayList<WriteOption> bfsOptionList = new ArrayList<>(); for (CopyOption option : options) { if (option == StandardCopyOption.REPLACE_EXISTING) { bfsOptionList.add(WriteOption.Standard.OVERWRITE); } } WriteOption []bfsOptions = new WriteOption[bfsOptionList.size()]; bfsOptionList.toArray(bfsOptions); try (OutputStream os = jTarget.getBfsFile().openWrite(bfsOptions)) { if (os == null) { throw new IOException(L.l("unable to write to file {0}", target.toUri())); } IoUtil.copy(is, os); } } }
/** * * @param source * @param target * @param options * @return * @see Files#copy(Path, Path, CopyOption...) */ @SafeVarargs public static Path copy(Path source, Path target, CopyOption... options) { try { return Files.copy(source, target, options); } catch (IOException e) { throw new UncheckedIOException(e); } }
/** * * @param in * @param target * @param options * @return * @see Files#copy(InputStream, Path, CopyOption...) */ @SafeVarargs public static long copy(InputStream in, Path target, CopyOption... options) { try { return Files.copy(in, target, options); } catch (IOException e) { throw new UncheckedIOException(e); } }