作为@assylias答案的补充:
如果您使用 Java 7,请完全放弃。相反,你想要的是。File
Path
要获取与文件系统上的路径匹配的对象,您需要执行以下操作:Path
Paths.get("path/to/file"); // argument may also be absolute
快速习惯它。请注意,如果仍然使用需要的 API,则有一个方法。File
Path
.toFile()
请注意,如果您不幸使用返回对象的 API,则始终可以执行以下操作:File
theFileObject.toPath()
但是在你的代码中,使用.系统。不假思索。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();
}
}