guwenren
package itcast.java16;

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

/*
 * 拷贝文本文件
 * 1,在D盘创建一个文件,用于存储C盘文件中的数据
 * 2,定义读取流和C盘文件关联。
 * 3,通过不断的读写完成数据存储
 * 4,关闭资源
 */
public class FileReaderWriterDemo1 {
    public static void main(String[] args) {
        copeA();
        copeB();
    }

    // 方式1单个字符读取
    public static void copeA() {
        FileWriter fw = null;
        FileReader fr = null;
        try {
            // 要读取的文件
            fr = new FileReader("F:\\MapDemo1.java");
            // 要写入的文件
            fw = new FileWriter("C:\\MapDemo1.txt");
            int len = 0;
            while ((len = fr.read()) != -1) {
                fw.write((char) len);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    }

    // 方式2单个字符数组读取
    public static void copeB() {
        FileWriter fw = null;
        FileReader fr = null;
        try {
            // 要读取的文件
            fr = new FileReader("F:\\MapDemo2.java");
            // 要写入的文件
            fw = new FileWriter("C:\\MapDemo2.txt");
            char[] chars = new char[1024];
            int len = 0;
            while ((len = fr.read(chars)) != -1) {
                fw.write(chars, 0, len);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    }
}

 

分类:

技术点:

相关文章:

  • 2021-09-24
  • 2021-05-05
  • 2021-11-04
  • 2021-11-15
  • 2021-04-11
  • 2021-11-21
  • 2021-10-27
  • 2021-09-17
猜你喜欢
  • 2021-08-15
  • 2021-10-16
  • 2021-08-15
  • 2021-11-07
  • 2021-08-15
  • 2021-11-07
  • 2021-08-15
相关资源
相似解决方案