黑马程序员技术交流社区

标题: IO流中拷贝文件并且存储到另一个文件 [打印本页]

作者: 江江会回来的    时间: 2015-9-20 22:56
标题: IO流中拷贝文件并且存储到另一个文件
package com_01;

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

public class IODemo3 {
        public static void main(String[] args) {
                FileWriter fw = null;
                FileReader fr = null;

                try {
                        fw = new FileWriter("D:\\a.txt");
                        fr = new FileReader("D:\\安装包\\PotPlayer_V1.6.52514.0_Setup.1422959344.exe");
                        // int ch = fr.read();
                        char[] chs = new char[100];
                        int len = 0;
                        while ((len = fr.read(chs)) != -1) {
                                fw.write(chs);
                                System.out.print(new String(chs, 0, len));
                        }
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        if (fr != null) {
                                try {
                                        fw.close();
                                        fr.close();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                }
        }
}



作者: Ralap军    时间: 2015-9-20 23:42
说说我的意见:
1、chs字符数组的长度最好定义为1024的整数倍
2、如果被拷贝的文件过大,没有定时刷新缓冲区,可能造成占用内存过多,甚至内存溢出
     所以最好在写入到缓冲区的数据差不多时,就用flush()刷新一下
3、finally里面,只判断了fr是否为null,fw没有判断,但也是需要进行null判断的。
作者: 江江会回来的    时间: 2015-9-21 01:21
Ralap军 发表于 2015-9-20 23:42
说说我的意见:
1、chs字符数组的长度最好定义为1024的整数倍
2、如果被拷贝的文件过大,没有定时刷新缓冲 ...

get到了 thankyou




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2