File和FileHelper类小封装

  • 对文件写入写出的小封装File类和FileHelper

File类

import java.io.*;

public class File{
    private String path;
    public File(String path) {
        this.path = path;
    }
    public String readToString() throws IOException {
        FileInputStream input = new FileInputStream(path);
        InputStreamReader reader = new InputStreamReader(input,"UTF-8");
        BufferedReader bufferedReader = new BufferedReader(reader);
        String context = "";
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            context += line + "\n";
        }
        bufferedReader.close();
        reader.close();
        input.close();
        return context;
    }
    public void writeString(String content) throws IOException{
        FileOutputStream output = new FileOutputStream(path);
        OutputStreamWriter writer = new OutputStreamWriter(output,"UTF-8");
        PrintWriter printer = new PrintWriter(writer);
        printer.print(content);
        printer.close();
        writer.close();
        output.close();
    }
}

Main实测

  • res文件夹在项目的根目录下
import java.io.IOException;

public class Main {

    public static void main(String[] args) throws IOException {
        File file1 = new File ("res/in.txt");
        File file2 = new File ("res/out.txt");
        String content = file1.readToString();
        file2.writeString(content);
    }
}

FileHelper类

public class FileHelper {
    public static void copy(File file1, File file2) throws IOException {
        file2.writeString(file1.readToString());
    }
}

Main实测

FileHelper.copy(file1,file2);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容