java复制文件的4种方式
一、使用FileStreams复制 这是最经典的方式将一个文件的内容复制到另一个文件中。 使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件B。 这是第一个方法的代码: 1 private static void copyFileUsingFileStreams(File source, File dest) 2 throws IOException { 3 InputStream input = null; 4 OutputStream output = null; 5 try { 6 input = new FileInputStream(source); 7 output = new FileOutputStream(dest); 8 byte[] buf = new byte[1024]; 9 int bytesRead; 10 while ((bytesRead = input.read(buf)) != -1) { 11 output.write(buf, 0, bytesRead); 12 } 13 } finally { 14 input.close(); 15 output.close(); 16 } 17 } 正如你所看到的我们执行几个读和写操作try的数据,所以这应该是一个低效率的,下一个方法我们将看到新的方式。