zoukankan      html  css  js  c++  java
  • JAVA 对文件的操作

    总结一下 遇到了Java中关于文件的4个操作,即:文件内容追加,文件内容清空,文件内容读取,文件删除。

    1  文件内容追加 ( 在已有的文件后面追加信息)

    public static void appendInfoToFile(String fileName, String info) {
      File file =new File(fileName);
      try {
          if(!file.exists()){
              file.createNewFile();
          }
          FileWriter fileWriter =new FileWriter(file, true);
          info =info +System.getProperty("line.separator");
          fileWriter.write(info);
          fileWriter.flush();
          fileWriter.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
    }


    2 文件内容清空 (清空已有的文件内容,以便下次重新写入新的内容)
    public static void clearInfoForFile(String fileName) {
      File file =new File(fileName);
      try {
          if(!file.exists()) {
              file.createNewFile();
          }
          FileWriter fileWriter =new FileWriter(file);
          fileWriter.write("");
          fileWriter.flush();
          fileWriter.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
    }

     3  读取文件内容

    3.1

       public static List<String> readInfoFromFile(String fileName) {
          File file =new File(fileName);
          if(!file.exists()) {
              return null;
          }
          List<String> resultStr =new ArrayList<String>();
          try {
              BufferedReader bufferedReader =new BufferedReader(new FileReader(file));
              String str =null;
              while(null !=(str=bufferedReader.readLine())) {
                  resultStr.add(str);
              }
          }catch (IOException e) {
              e.printStackTrace();
          }
          return resultStr;
      }

     

    3.2  读取全部内容
    import cn.hutool.core.io.FileUtil;
    String content = FileUtil.readUtf8String(read_file);

    4 删除文件(如果存在就删除
    //  if (read_file.exists()) read_file.delete();
  • 相关阅读:
    January 25th, 2018 Week 04th Thursday
    January 24th, 2018 Week 04th Wednesday
    January 23rd, 2018 Week 04th Tuesday
    January 22nd, 2018 Week 04th Monday
    January 21st, 2018 Week 3rd Sunday
    January 20th, 2018 Week 3rd Saturday
    January 19th, 2018 Week 3rd Friday
    January 18th, 2018 Week 03rd Thursday
    January 17th, 2018 Week 03rd Wednesday
    January 16th, 2018 Week 03rd Tuesday
  • 原文地址:https://www.cnblogs.com/wy919/p/15612125.html
Copyright © 2011-2022 走看看