用Java复制文件并替换现有目标

com*_*een 38 java replace copy file

我正在尝试使用java.nio.file.Files复制文件,如下所示:

Files.copy(cfgFilePath, strTarget, StandardCopyOption.REPLACE_EXISTING);
Run Code Online (Sandbox Code Playgroud)

问题是Eclipse说"文件类型中的方法副本(Path,Path,CopyOption ...)不适用于参数(File,String,StandardCopyOption)"

我在Win7 x64上使用Eclipse和Java 7.我的项目设置为使用Java 1.6兼容性.

有没有解决方案,或者我必须创建这样的解决方法:

File temp = new File(target);

if(temp.exists())
  temp.delete();
Run Code Online (Sandbox Code Playgroud)

谢谢.

ass*_*ias 100

您需要传递Path参数,如错误消息所述:

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);
Run Code Online (Sandbox Code Playgroud)

这假设你strTarget是一条有效的道路.


fge*_*fge 10

作为@assylias答案的补充:

如果您使用Java 7,请File完全删除.你想要的是什么Path.

要获得Path与文件系统上的路径匹配的对象,您可以:

Paths.get("path/to/file"); // argument may also be absolute
Run Code Online (Sandbox Code Playgroud)

快速习惯它.需要注意的是,如果你仍然使用需要的API File,Path有一个.toFile()方法.

请注意,如果您处于使用返回File对象的API的不幸情况,您始终可以执行以下操作:

theFileObject.toPath()
Run Code Online (Sandbox Code Playgroud)

但是在你的代码中,请使用Path.系统化.没有第二个想法.

编辑使用NIO使用1.6将文件复制到另一个文件可以这样做; 请注意,该Closer课程受到番石榴的启发:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • [文件**s**](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) != [文件](https://docs.oracle .com/javase/7/docs/api/java/io/File.html)。File**s** 是 nio 的一部分。请不要写 60 行样板以避免使用 Files.copy。 (2认同)

ABH*_*HRI 5

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());
        }
    }

}
Run Code Online (Sandbox Code Playgroud)