用Java复制文件并替换现有目标
我正在尝试使用java.nio.file.Files复制文件,如下所示:
Files.copy(cfgFilePath, strTarget, StandardCopyOption.REPLACE_EXISTING);问题在于Eclipse表示“文件类型中的方法copy(Path,Path,CopyOption
…)不适用于参数(File,String,StandardCopyOption)”
我在Win7 x64上使用Eclipse和Java 7。我的项目设置为使用Java 1.6兼容性。
有解决方案吗,还是我必须创建类似的解决方法:
File temp = new File(target);if(temp.exists())
  temp.delete();
谢谢。
回答:
作为@assylias答案的补充:
如果您使用Java 7,请File完全删除。您想要的是Path。
要获得Path与文件系统上的路径匹配的对象,请执行以下操作:
Paths.get("path/to/file"); // argument may also be absolute快速习惯它。需要注意的是,如果你仍然使用需要的API File,Path有一个.toFile()方法。
请注意,如果不幸的是您使用返回File对象的API ,则始终可以执行以下操作:
theFileObject.toPath()但在您的代码中,使用Path。系统地。不用再想了。
 可以使用NIO使用1.6将文件复制到另一个文件。请注意,该Closer课程是由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();
    }
}
以上是 用Java复制文件并替换现有目标 的全部内容, 来源链接: utcz.com/qa/422708.html
