通过字符流来实现文件复制()

java通过字符流来实现文件复制(异常捕获和异常抛出)

异常抛出方法

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class _文件复制抛出异常{
    public static void main(String[] args) throws IOException {
        FileWriter writer = null;
        FileReader reader = null;
        reader = new FileReader("D:\\1.txt");
        writer = new FileWriter("D:\\2.txt");
        char[] cs = new char[100];
        int len = -1;
        while ((len = reader.read(cs)) != -1){
            writer.write(cs);
            writer.flush();
        }
        writer.close();
        reader.close();
    }
}

异常捕获方法

import java.io.*;

public class _文件复制捕获异常 {
    public static void main(String[] args) {
        FileReader reader = null;
        FileWriter writer = null;
        try {
            reader = new FileReader("D:\\1.txt");
            writer = new FileWriter("D:\\2.txt",true);
            char[] cs = new char[50];
            int len = -1;
            while ((len = reader.read(cs)) != -1) {
                writer.write(cs, 0, len);
            }
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    reader = null;
                }
            }
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    writer = null;
                }
            }
        }
    }
}

上一篇:数据处理:我的csv三元组转换成json格式


下一篇:Qt 寿命倒计时设计实现