侧边栏壁纸
博主头像
小顺

一帆风顺 ⛵️⛵️⛵️

  • 累计撰写 70 篇文章
  • 累计创建 0 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

I/O(FileReader和FileWriter实现txt复制)

小顺
2021-08-15 / 0 评论 / 0 点赞 / 28 阅读 / 266 字

第一版:

第一版中没有buffer,最后的finally也是错的

package com.apesblog.day_26;

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

public class Test2 {

    public static void main(String[] args) {
        FileReader fileReader = null;
        FileWriter fileWriter = null;
        try {
            File file = new File("src/com/apesblog/day_26/hello.txt");
            fileReader = new FileReader(file);
            int read;
            StringBuilder stringBuilder = new StringBuilder();
            while ((read = fileReader.read()) != -1) {
                stringBuilder.append((char) read);
            }
            System.out.print(stringBuilder);
            File file2 = new File(file.getParent(), "copy.txt");
            fileWriter = new FileWriter(file2,true);
            fileWriter.write(stringBuilder.append("\n").toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

第二版

package com.apesblog.day_26;

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

public class Test3 {

    public static void main(String[] args) {
        FileReader fileReader = null;
        FileWriter fileWriter = null;
        try {
            File file = new File("src/com/apesblog/day_26/hello.txt");
            fileReader = new FileReader(file);
            int read;
            StringBuilder stringBuilder = new StringBuilder();
            char[] buffer = new char[5];
            while ((read = fileReader.read(buffer)) != -1) {
                stringBuilder.append(buffer, 0, read);
            }
            System.out.print(stringBuilder);
            File file2 = new File(file.getParent(), "copy.txt");
            fileWriter = new FileWriter(file2, true);
            fileWriter.write(stringBuilder.append("\n").toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null)
                    fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileWriter != null)
                    fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
0

评论区