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

时间:2013-06-18 13:00:55

标签: java file replace copy

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

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

问题是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();

感谢。

4 个答案:

答案 0 :(得分:90)

您需要传递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);

假设您的strTarget是有效路径。

答案 1 :(得分:9)

作为@assylias答案的补充:

如果您使用Java 7,请完全删除File。您想要的是Path

要获得与文件系统上的路径匹配的Path对象,请执行以下操作:

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

快速适应它。请注意,如果您仍然使用需要File的API,则Path具有.toFile()方法。

请注意,如果您处于使用返回File个对象的API的不幸情况,您可以随时执行:

theFileObject.toPath()

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

编辑使用NIO使用1.6将文件复制到另一个文件可以这样做;请注意,Guava启发了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();
    }
}

答案 2 :(得分:1)

strTarget是一个“String”对象而不是“Path”对象

答案 3 :(得分:0)

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

}