美文网首页
File和FileHelper类小封装

File和FileHelper类小封装

作者: 迷路的丸子 | 来源:发表于2018-08-24 16:46 被阅读0次
    • 对文件写入写出的小封装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);
    

    相关文章

      网友评论

          本文标题:File和FileHelper类小封装

          本文链接:https://www.haomeiwen.com/subject/dshiiftx.html