java实现文件的复制
直接上源码:
1 package copyFile; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.FileOutputStream; 8 import java.io.IOException; 9 10 /** 11 *准备工作:准备一首MP3音乐,取名为1.mp3。将该音乐文件复制到D盘下。该文件的路径为 D:\1.mp3 12 *任务目的:实现文件的复制。将1.mp3复制为2.mp3。 13 */ 14 public class FileCopy { 15 public static void main(String[] args) { 16 File sourceFile = new File("d:/2.mp3");//源文件 17 File targetFile = new File("d:/3.mp3");//目标文件 18 byte[] buf = new byte[1024];//缓冲区的大小 19 if(!sourceFile.exists()){ //判断源文件是否存在,不存在就退出该程序 20 System.out.println("源文件不存在"); 21 return; 22 } 23 if(targetFile.exists()){//判断目标文件时候存在,存在就删除掉 24 targetFile.delete(); 25 } 26 try { 27 targetFile.createNewFile();//创建空的目标文件 28 } catch (IOException e) { 29 e.printStackTrace(); 30 } 31 try { 32 FileInputStream fis = new FileInputStream(sourceFile);//获取源文件的输入流 33 FileOutputStream fos = new FileOutputStream(targetFile);//获取目标文件的输出流 34 BufferedInputStream bis = new BufferedInputStream(fis); 35 BufferedOutputStream bos = new BufferedOutputStream(fos); 36 int size = -1; 37 while((size=bis.read(buf))!=-1){//如果返回结果为-1,就退出循环 38 bos.write(buf,0,size); 39 bos.flush(); 40 } 41 fis.close();//关闭输入流 42 fos.close();//关闭输出流 43 } catch (Exception e) { 44 e.printStackTrace(); 45 } 46 } 47 }