你知道java实现文件复制功能应该怎样做吗?下面要给大家分享的就是java复制文件的几种方式,一起通过下文来进行一下了解吧。
1、使用FileChannel
public static void copyNio(String source, String dest)
{
FileChannel input = null;
FileChannel output = null;
try
{
input = new FileInputStream(new File(from))
.getChannel();
output = new FileOutputStream(new File(to))
.getChannel();
output.transferFrom(input, 0, input.size());
}
catch (Exception e)
{
Log.w(TAG + "copyNio", "error occur while copy", e);
}
finally
{
safelyClose(TAG + "copyNio", input);
safelyClose(TAG + "copyNio", output);
}
}2、使用Java7的Files类复制
private static void copyFileUsingJava7Files(File source, File dest) throws IOException
{
Files.copy(source.toPath(), dest.toPath());
}3、使用FileStreams复制
public static void copy(String source, String dest, int bufferSize)
{
InputStream in = null;
OutputStream out = null;
try
{
in = new FileInputStream(new File(source));
out = new FileOutputStream(new File(dest));
byte[] buffer = new byte[bufferSize];
int len;
while ((len = in .read(buffer)) > 0)
{
out.write(buffer, 0, len);
}
}
catch (Exception e)
{
Log.w(TAG + ":copy", "error occur while copy", e);
}
finally
{
safelyClose(TAG + ":copy", in );
safelyClose(TAG + ":copy", out);
}
}4、使用Apache Commons IO复制
private static void copyFileByApacheCommonsIO(File source, File dest) throws IOException
{
FileUtils.copyFile(source, dest);
}以上的四种方式你都可以去尝试一下哦,更多java基础知识,欢迎继续关注奇Q工具网来进行了解吧。
推荐阅读: