Joã*_*lva 30
不,没有内置方法可以做到这一点.最接近你想要完成的是transferFrom方法FileOutputStream,如下所示:
FileChannel src = new FileInputStream(file1).getChannel();
FileChannel dest = new FileOutputStream(file2).getChannel();
dest.transferFrom(src, 0, src.size());
Run Code Online (Sandbox Code Playgroud)
并且不要忘记处理异常并关闭finally块中的所有内容.
Mad*_*ddy 24
如果你想要懒惰并且__CODE__
从Apache IOCommons 编写最少的代码使用
不是.每个长期的Java程序员都有自己的实用带,包括这样的方法.这是我的.
public static void copyFileToFile(final File src, final File dest) throws IOException
{
copyInputStreamToFile(new FileInputStream(src), dest);
dest.setLastModified(src.lastModified());
}
public static void copyInputStreamToFile(final InputStream in, final File dest)
throws IOException
{
copyInputStreamToOutputStream(in, new FileOutputStream(dest));
}
public static void copyInputStreamToOutputStream(final InputStream in,
final OutputStream out) throws IOException
{
try
{
try
{
final byte[] buffer = new byte[1024];
int n;
while ((n = in.read(buffer)) != -1)
out.write(buffer, 0, n);
}
finally
{
out.close();
}
}
finally
{
in.close();
}
}
Run Code Online (Sandbox Code Playgroud)
从Java 7开始,您可以使用Files.copy()Java的标准库.
您可以创建一个包装器方法:
public static void copy(String sourcePath, String destinationPath) throws IOException {
Files.copy(Paths.get(sourcePath), new FileOutputStream(destinationPath));
}
Run Code Online (Sandbox Code Playgroud)
可以通过以下方式使用:
copy("source.txt", "dest.txt");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50227 次 |
| 最近记录: |