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

发布于 2021-08-13  40 次阅读


第一版:

第一版中没有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();
            }
        }

    }
}