作为 @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
。不要犹豫。
编辑 使用1.6版本的NIO将文件复制到另一个文件可以这样做;请注意,Closer
类受到Guava的启发:
public final class Closer
implements Closeable
{
private final List<Closeable> closeables = new ArrayList<Closeable>();
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;
}
}
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();
}
}