码迷,mamicode.com
首页 > 编程语言 > 详细

java实现文件的复制

时间:2014-10-09 01:43:37      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   java   文件   sp   

直接上源码:

 1 package copyFile;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 
 8 /**
 9  *准备工作:准备一首MP3音乐,取名为1.mp3。将该音乐文件复制到D盘下。该文件的路径为  D:\1.mp3
10  *任务目的:实现文件的复制。将1.mp3复制为2.mp3。
11  */
12 public class FileCopy {
13     public static void main(String[] args) {
14         FileInputStream fis = null;
15         FileOutputStream fos = null;
16         File sourceFile = new File("d:/1.mp3");//源文件
17         File targetFile = new File("d:/2.mp3");//目标文件
18         byte[] buf = new byte[1024];//建立1K大小的缓冲区
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             fis = new FileInputStream(sourceFile);//获取源文件的输入流
33             fos = new FileOutputStream(targetFile);//获取目标文件的输出流
34             while(fis.read(buf)!=-1){//while循环,文件开始复制
35                 fos.write(buf);
36             }
37             fis.close();//关闭输入流
38             fos.close();//关闭输出流
39         } catch (Exception e) {
40             e.printStackTrace();
41         }
42     }
43 }

 

java实现文件的复制

标签:style   blog   color   io   os   ar   java   文件   sp   

原文地址:http://www.cnblogs.com/miyin/p/4011508.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!