zoukankan      html  css  js  c++  java
  • IO流读写文本文件

    IO流读写文本文件

    import java.io.BufferedReader;
    import java.io.FileReader;

    public class ReadFile {
    FileReader reader = null;
    String filePath = "";
    BufferedReader br = null;

    public ReadFile(String filePath) throws Exception{
    this.filePath = filePath;
    reader = new FileReader(filePath);
    br = new BufferedReader(reader);
    }

    public void initReader() throws Exception{
    reader = new FileReader(filePath);
    br = new BufferedReader(reader);
    }
    //读文件的一行
    public String readLine() throws Exception{
    String lineString = "";
    if((lineString = br.readLine()) != null){
    return lineString;
    }
    return null;
    }
    //读整个文件
    public String readFileToString() throws Exception{
    String lineString = "";
    StringBuffer buffer = new StringBuffer();
    while((lineString = br.readLine()) != null){
    buffer.append(lineString).append("/n");
    }
    return buffer.toString();
    }

    public void closeReader() throws Exception{
    br.close();
    reader.close();
    }

    public String getFilePath() {
    return filePath;
    }

    public void setFilePath(String filePath) {
    this.filePath = filePath;
    }

    //写文件

    public static void write(String path, String content) {
    String s = new String();
    String s1 = new String();
    try {
    File f = new File(path);
    if (f.exists()) {
    System.out.println("文件存在");
    } else {
    System.out.println("文件不存在,正在创建...");
    if (f.createNewFile()) {
    System.out.println("文件创建成功!");
    } else {
    System.out.println("文件创建失败!");
    }

    }
    BufferedReader input = new BufferedReader(new FileReader(f));

    while ((s = input.readLine()) != null) {
    s1 += s + "/n";
    }
    System.out.println("文件内容:" + s1);
    input.close();
    s1 += content;

    BufferedWriter output = new BufferedWriter(new FileWriter(f));
    output.write(s1);
    output.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }


    }

     

    攀登者IT技术交流总群:141098671(500人) || 攀登者IT【.Net】精英:172663374 || 攀登者IT【Java】精英:216931633欢迎你的加入进行技术探讨!加群时请写好技术方向,否则不批准!

  • 相关阅读:
    scss使用指南--每天一点
    Egret引擎开发基础(一)
    vue-awesome-swiper使用自动轮播和循环轮播不生效(loop和autoplay)
    Vue项目中title的设置,使用document.title返回时不生效
    charles系列破解激活注册码
    Vscode中vue项目中无法对js进行提示
    JS数组与对象的遍历方法大全
    手把手教你用webpack3搭建react项目(开发环境和生产环境)(二)
    服务器安装redis-stat和easyNmon
    Shell备份数据库
  • 原文地址:https://www.cnblogs.com/liyumei/p/2503903.html
Copyright © 2011-2022 走看看