Copy file in Java and replace existing target

前端 未结 4 844
青春惊慌失措
青春惊慌失措 2020-12-02 22:36

I\'m trying to copy a file with java.nio.file.Files like this:

Files.copy(cfgFilePath, strTarget, StandardCopyOption.REPLACE_EXISTING);

The

相关标签:
4条回答
  • 2020-12-02 23:00

    You need to pass Path arguments as explained by the error message:

    Path from = cfgFilePath.toPath(); //convert from File to Path
    Path to = Paths.get(strTarget); //convert from String to Path
    Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
    

    That assumes your strTarget is a valid path.

    0 讨论(0)
  • 2020-12-02 23:10

    strTarget is a "String" object and not a "Path" object

    0 讨论(0)
  • 2020-12-02 23:13
    package main.java;
    
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardCopyOption;
    
    public class CopyFileOnExist {
    
        public static void main(String[] args)  {
    
            Path sourceDirectory = Paths.get("C:/Users/abc/Downloads/FileNotFoundExceptionExample/append.txt");
            Path targetDirectory = Paths.get("C:/Users/abc/Downloads/FileNotFoundExceptionExample/append5.txt");
    
            //copy source to target using Files Class
            try {
                Files.copy(sourceDirectory, targetDirectory,StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-02 23:23

    As a complement to @assylias' answer:

    If you use Java 7, drop File entirely. What you want is Path instead.

    And to get a Path object matching a path on your filesystem, you do:

    Paths.get("path/to/file"); // argument may also be absolute
    

    Get used to it real fast. Note that if you still use APIs which require File, Path has a .toFile() method.

    Note that if you are in the unfortunate case where you use an API which returns File objects, you can always do:

    theFileObject.toPath()
    

    But in code of yours, use Path. Systematically. Without a second thought.

    EDIT Copying a file to another using 1.6 using NIO can be done as such; note that the Closer class is inspited by Guava:

    public final class Closer
        implements Closeable
    {
        private final List<Closeable> closeables = new ArrayList<Closeable>();
    
        // @Nullable is a JSR 305 annotation
        public <T extends Closeable> T add(@Nullable final T closeable)
        {
            closeables.add(closeable);
            return closeable;
        }
    
        public void closeQuietly()
        {
            try {
                close();
            } catch (IOException ignored) {
            }
        }
    
        @Override
        public void close()
            throws IOException
        {
            IOException toThrow = null;
            final List<Closeable> l = new ArrayList<Closeable>(closeables);
            Collections.reverse(l);
    
            for (final Closeable closeable: l) {
                if (closeable == null)
                    continue;
                try {
                    closeable.close();
                } catch (IOException e) {
                    if (toThrow == null)
                        toThrow = e;
                }
            }
    
            if (toThrow != null)
                throw toThrow;
        }
    }
    
    // Copy one file to another using NIO
    public static void doCopy(final File source, final File destination)
        throws IOException
    {
        final Closer closer = new Closer();
        final RandomAccessFile src, dst;
        final FileChannel in, out;
    
        try {
            src = closer.add(new RandomAccessFile(source.getCanonicalFile(), "r");
            dst = closer.add(new RandomAccessFile(destination.getCanonicalFile(), "rw");
            in = closer.add(src.getChannel());
            out = closer.add(dst.getChannel());
            in.transferTo(0L, in.size(), out);
            out.force(false);
        } finally {
            closer.close();
        }
    }
    
    0 讨论(0)
提交回复
热议问题