Java实现文件拷贝的七种方式
Java实现文件拷贝的七种方式,分别是:FileInputStream、FileOutputStream、BufferedInputStream、BufferedOutputStream、FileChannel、Files.copy()方法以及Apache Commons IO的copy()方法。下面将详细介绍这七种方式的使用方法。
1. FileInputStream与FileOutputStream
FileInputStream、FileOutputStream是Java IO流中的基本流,它们可以实现文件的拷贝,但是由于它们的读写操作是一个字节一个字节的进行,所以拷贝的效率较低。
//使用FileInputStream与FileOutputStream拷贝文件 InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } is.close(); os.close();
2. BufferedInputStream与BufferedOutputStream
BufferedInputStream与BufferedOutputStream是FileInputStream和FileOutputStream的包装类,它们可以通过缓冲区的方式,提高文件的拷贝效率。
//使用BufferedInputStream与BufferedOutputStream拷贝文件 InputStream is = new BufferedInputStream(new FileInputStream(src)); OutputStream os = new BufferedOutputStream(new FileOutputStream(dest)); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } is.close(); os.close();
3. FileChannel
FileChannel是Java NIO中的类,它可以实现文件的快速拷贝,拷贝效率要比FileInputStream和FileOutputStream高出许多。
//使用FileChannel拷贝文件 FileChannel sourceChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destChannel.close();
4. Files.copy()方法
Files.copy()方法是Java 7中提供的一个新的API,它可以实现文件的拷贝,而且拷贝的效率也比较高。
//使用Files.copy()方法拷贝文件 Files.copy(Paths.get(src), Paths.get(dest), StandardCopyOption.REPLACE_EXISTING);
5. Apache Commons IO的copy()方法
Apache Commons IO是Apache的一个开源项目,它提供了很多实用的工具类,其中提供了一个copy()方法,可以实现文件的拷贝,拷贝效率也比较高。
//使用Apache Commons IO的copy()方法拷贝文件 FileUtils.copyFile(new File(src), new File(dest));
以上就是Java实现文件拷贝的七种方式,可以根据实际需要,选择适合自己的拷贝方式。