java file reading and writing tool class sharing

  • 2021-01-18 06:29:23
  • OfStack

This article example for everyone to share java file reading and writing tool class specific code, for your reference, the specific content is as follows


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

/**
 * <p> File manipulation tool class <p>
 * @version 1.0
 * @author li_hao
 * @date 2017 years 1 month 18 day 
 */
@SuppressWarnings({"resource","unused"})
public class FileUtils {
  
  /**
   *  To obtain windows/linux The project root directory of 
   * @return
   */
  public static String getConTextPath(){
    String fileUrl = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    if("usr".equals(fileUrl.substring(1,4))){
      fileUrl = (fileUrl.substring(0,fileUrl.length()-16));//linux
    }else{
      fileUrl = (fileUrl.substring(1,fileUrl.length()-16));//windows
    }
    return fileUrl;
  }
    
  /**
   *  String to array 
   * @param str  string 
   * @param splitStr  The separator 
   * @return
   */
  public static String[] StringToArray(String str,String splitStr){
    String[] arrayStr = null;
    if(!"".equals(str) && str != null){
      if(str.indexOf(splitStr)!=-1){
        arrayStr = str.split(splitStr);
      }else{
        arrayStr = new String[1];
        arrayStr[0] = str;
      }
    }
    return arrayStr;
  }
    
  /**
   *  Read the file 
   * 
   * @param Path
   * @return
   */
  public static String ReadFile(String Path) {
    BufferedReader reader = null;
    String laststr = "";
    try {
      FileInputStream fileInputStream = new FileInputStream(Path);
      InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
      reader = new BufferedReader(inputStreamReader);
      String tempString = null;
      while ((tempString = reader.readLine()) != null) {
        laststr += tempString;
      }
      reader.close();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return laststr;
  }
    
  /**
   *  Gets the names of all the files in the folder  +  Fuzzy queries (When fuzzy queries are not needed, queryStr The empty or null ) 
   * 1. When the path doesn't exist, map return retType A value of 1
   * 2. When the path is the file path, map return retType A value of 2 , the file name fileName Value is filename 
   * 3. When there is a folder under the path, map return retType A value of 3 , list of file names fileNameList , folder names list folderNameList
   * @param folderPath  The path 
   * @param queryStr  Fuzzy query string 
   * @return
   */
  public static HashMap<String, Object> getFilesName(String folderPath , String queryStr) {
    HashMap<String, Object> map = new HashMap<>();
    List<String> fileNameList = new ArrayList<>();// List of file names 
    List<String> folderNameList = new ArrayList<>();// List of folder names 
    File f = new File(folderPath);
    if (!f.exists()) { // Path does not exist 
      map.put("retType", "1");
    }else{
      boolean flag = f.isDirectory();
      if(flag==false){ // The path is a file 
        map.put("retType", "2");
        map.put("fileName", f.getName());
      }else{ // The path is folder 
        map.put("retType", "3");
        File fa[] = f.listFiles();
        queryStr = queryStr==null ? "" : queryStr;// if queryStr For the incoming null, Then replace it with empty ( indexOf The match value cannot be null ) 
        for (int i = 0; i < fa.length; i++) {
          File fs = fa[i];
          if(fs.getName().indexOf(queryStr)!=-1){
             if (fs.isDirectory()) {
               folderNameList.add(fs.getName());
             } else {
               fileNameList.add(fs.getName());
             }
           }
        }
        map.put("fileNameList", fileNameList);
        map.put("folderNameList", folderNameList);
      }
    }
    return map;
  }
  
  /**
   *  Reads the file in action units until the end 1 line 
   * @param filePath
   * @return
   */
  public static List<String> readFileContent(String filePath) { 
    BufferedReader reader = null;
    List<String> listContent = new ArrayList<>();
    try { 
      reader = new BufferedReader(new FileReader(filePath)); 
      String tempString = null; 
      int line = 1; 
      // 1 Time to read 1 Line until it is read in null End of file  
      while ((tempString = reader.readLine()) != null) {
        listContent.add(tempString);
        line++;
      } 
      reader.close(); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } finally { 
      if (reader != null) { 
        try { 
          reader.close(); 
        } catch (IOException e1) { 
        } 
      } 
    }
    return listContent;
  } 
  
  /**
   *  Reads the specified row data   , pay attention to: 0 For the start line 
   * @param filePath
   * @param lineNumber
   * @return
   */
  public static String readLineContent(String filePath,int lineNumber){
    BufferedReader reader = null;
    String lineContent="";
    try {
      reader = new BufferedReader(new FileReader(filePath));
      int line=0;
      while(line<=lineNumber){
        lineContent=reader.readLine();
        line++;
      }
      reader.close();
    } catch (IOException e) { 
      e.printStackTrace(); 
    } finally { 
      if (reader != null) { 
        try { 
          reader.close(); 
        } catch (IOException e1) { 
        } 
      } 
    } 
    return lineContent;
  }
  
  /**
   *  Read from the beginLine to endLine Data (including beginLine and endLine ), note: 0 For the start line 
   * @param filePath
   * @param beginLineNumber  Start line 
   * @param endLineNumber  End line 
   * @return
   */
  public static List<String> readLinesContent(String filePath,int beginLineNumber,int endLineNumber){
    List<String> listContent = new ArrayList<>();
    try{
      int count = 0;
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
      String content = reader.readLine();
      while(content !=null){
        if(count >= beginLineNumber && count <=endLineNumber){
          listContent.add(content);
        }  
        content = reader.readLine();
        count++;  
      }
    } catch(Exception e){
    }
    return listContent;
  }
    
  /**
   *  Read all data from several files 
   * @param listFilePath
   * @return
   */
  public static List<String> readFileContent_list(List<String> listFilePath) { 
    List<String> listContent = new ArrayList<>();
    for(String filePath : listFilePath){
       File file = new File(filePath);
       BufferedReader reader = null;
      try { 
        reader = new BufferedReader(new FileReader(file)); 
        String tempString = null; 
        int line = 1; 
        // 1 Time to read 1 Line until it is read in null End of file  
        while ((tempString = reader.readLine()) != null) {
          listContent.add(tempString);
          line++;
        } 
        reader.close(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
      } finally { 
        if (reader != null) { 
          try { 
            reader.close(); 
          } catch (IOException e1) { 
          } 
        } 
      }
    }
    return listContent;
  }
  
  /**
   *  File data write (if folder and file do not exist, create first, then write) 
   * @param filePath
   * @param content
   * @param flag true: If the file exists and the content exists, the content is appended with a newline; false: If the file exists and the content exists, the content is replaced 
   */
  public static String fileLinesWrite(String filePath,String content,boolean flag){
    String filedo = "write";
    FileWriter fw = null;
    try {
      File file=new File(filePath);
      // If the folder does not exist, the folder is created 
      if (!file.getParentFile().exists()){
        file.getParentFile().mkdirs();
      }
      if(!file.exists()){// If the file does not exist, the file is created , Write the first 1 line 
        file.createNewFile();
        fw = new FileWriter(file);
        filedo = "create";
      }else{// If the file exists , The content is appended or replaced 
        fw = new FileWriter(file, flag);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
      PrintWriter pw = new PrintWriter(fw);
      pw.println(content);
      pw.flush();
    try {
      fw.flush();
      pw.close();
      fw.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return filedo;
  }
      
  /**
   *  Write files 
   * @param ins
   * @param out
   */
  public static void writeIntoOut(InputStream ins, OutputStream out) {
    byte[] bb = new byte[10 * 1024];
    try {
      int cnt = ins.read(bb);
      while (cnt > 0) {
        out.write(bb, 0, cnt);
        cnt = ins.read(bb);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        out.flush();
        ins.close();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
  /**
   *  judge list Whether the elements are identical in the true, Otherwise returns false ) 
   * @param list
   * @return
   */
  private static boolean hasSame(List<? extends Object> list){ 
    if(null == list) 
      return false; 
    return 1 == new HashSet<Object>(list).size(); 
  } 
  
  /**
   *  judge list Is there a duplicate element in the true, Otherwise returns false ) 
   * @param list
   * @return
   */
  private static boolean hasSame2(List<? extends Object> list){ 
    if(null == list) 
      return false; 
    return list.size() == new HashSet<Object>(list).size(); 
  } 
  
  /**
   *  increase / Reduce the number of days 
   * @param date
   * @param num
   * @return
   */
  public static Date DateAddOrSub(Date date, int num) { 
    Calendar startDT = Calendar.getInstance(); 
    startDT.setTime(date); 
    startDT.add(Calendar.DAY_OF_MONTH, num); 
    return startDT.getTime(); 
  }
  
}

Related articles: