第一种:
可以读取任何类型的文件
- public static void copy(String src, String des){
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try {
- File file1 = new File(src);
- File file2 = new File(des);
- fis = new FileInputStream(file1);
- fos = new FileOutputStream(file2);
- byte[] b = new byte[1024];
- int len;
- while((len = fis.read(b,0,b.length))!=-1){//len是读到的字符数
- fos.write(b,0,len);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- if(fos!=null)
- fos.close();
- }catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- if(fis!=null)
- fis.close();
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- System.out.println("复制完毕");
- }
- }
- }
- }
复制代码
第二种:
比较适合纯文本文件
- //每一个字符都有对应的编码 每一个编码不一定有相对应的字符所以char型只能读取文本;
- public static void copy2(String src, String des){
- FileReader bufr = null;
- FileWriter bufw = null;
- try {
- bufr = new FileReader(src);
- bufw = new FileWriter(des);
- char[] b = new char[1024*1024*8];
- int len;
- while((len = bufr.read(b,0,b.length))!=-1){//len是读到的字符数
- System.out.println(len);//4375507 6456312
- bufw.write(b,0,len);
- bufw.flush();
- //bufw.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- if(bufw!=null)
- bufw.close();
- }catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- if(bufr!=null)
- bufr.close();
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- System.out.println("复制完毕");
- }
- }
- }
- }
- }
复制代码 |
|