
java中复制文件的要领:(引荐:java视频教程)
一、运用FileStreams复制
这是最典范的体式格局将一个文件的内容复制到另一个文件中。 运用FileInputStream读取文件A的字节,运用FileOutputStream写入到文件B。 这是第一个要领的代码:
private static void copyFileUsingFileStreams(File source, File dest) throws IOException { InputStream input = null; OutputStream output = null; try { input = new FileInputStream(source); output = new FileOutputStream(dest); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = input.read(buf)) != -1) { output.write(buf, 0, bytesRead); } } finally { input.close(); output.close(); } }
正如你所看到的我们实行几个读和写操纵try的数据,所以这应当是一个低效率的,下一个要领我们将看到新的体式格局。
二、运用FileChannel复制
Java NIO包含transferFrom要领,依据文档应当比文件流复制的速率更快。 这是第二种要领的代码:
private static void copyFileUsingFileChannels(File source, File dest) throws IOException { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(source).getChannel(); outputChannel = new FileOutputStream(dest).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } finally { inputChannel.close(); outputChannel.close(); } }
三、运用Commons IO复制
Apache Commons IO供应拷贝文件要领在其FileUtils类,可用于复制一个文件到另一个处所。它异常方便运用Apache Commons FileUtils类时,您已运用您的项目。基本上,这个类运用Java NIO FileChannel内部。 这是第三种要领的代码:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException { FileUtils.copyFile(source, dest); }
该要领的中心代码以下:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size) { count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos; pos += output.transferFrom(input, pos, count); } } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(input); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
因而可知,运用Apache Commons IO复制文件的道理就是上述第二种要领:运用FileChannel复制
四、运用Java7的Files类复制
假如你有一些履历在Java 7中你可能会晓得,能够运用复制要领的Files类文件,从一个文件复制到另一个文件。 这是第四个要领的代码:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException { Files.copy(source.toPath(), dest.toPath()); }
更多java学问请关注java基础教程栏目。
以上就是java怎样复制文件?的细致内容,更多请关注ki4网别的相干文章!