IO拷贝文件两种方式

时间:2019-09-09
本文章向大家介绍IO拷贝文件两种方式,主要包括IO拷贝文件两种方式使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
package CoreJavaPractice;

import java.io.*;
public class Practice_2 {
    public static void main(String[] args) throws IOException {
        
        copy_2();
        
        
    }
    public static void copy_2() throws IOException
    {
        FileWriter fw = null;
        FileReader fr = null;
        try
        {
            fw = new FileWriter("Demo_copy2.txt");
            fr = new FileReader("Demo.txt");
            
            char[] buf = new char[1024];
            int len = 0;
            while((len = fr.read(buf)) != -1)
            {
                fw.write(buf,0,len);
            }
        }
        catch(IOException e)
        {
            throw new RuntimeException("读写失败");
        }
        finally
        {
            if(fr!=null)
            {
                try
                {
                    fr.close();
                }
                catch(IOException e)
                {
                }
                try
                {
                    fw.close();
                }
                catch(IOException e)
                {
                }
                
            }
        }
    }
    
    public static void copy_1() throws IOException
    {
    // 拷贝一个文件到当前目录下
    // 创建目的地
    FileWriter fw = new FileWriter("Demo_copy.txt");
    
    //与已有文件关联
    FileReader fr = new FileReader("Demo.txt");
    
    int len = 0;
    while((len=fr.read())!=-1)
    {
        fw.write(len);
    }
    fr.close();
    fw.close();
    }
    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}

原文地址:https://www.cnblogs.com/zxl1010/p/11490047.html