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

我正在尝试使用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(); 

谢谢。

作为@assylias答案的补充:

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

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

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

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

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

 theFileObject.toPath() 

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

编辑使用NIO使用1.6将文件复制到另一个文件可以这样做; 请注意, Closer类受到Guava的启发:

 public final class Closer implements Closeable { private final List closeables = new ArrayList(); // @Nullable is a JSR 305 annotation public  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 l = new ArrayList(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(); } } 

您需要传递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是一个有效的路径。

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