1 package com.dingheng.utils; 2 3 import java.io.*; 4 import java.util.ArrayList; 5 import java.util.List; 6 7 /** 8 * TODO 9 * 10 * @ClassName: FileUtils 11 * @author: DingH 12 * @since: 2019/5/28 9:05 13 */ 14 public class FileUtils { 15 16 /** 17 * 一行写入文件,末尾自动添加\n 18 * @param path 19 * @param line 20 * @param is_append 21 * @param encode 22 */ 23 public static void writeLog(String path, String line, boolean is_append, String encode) 24 { 25 try 26 { 27 File file = new File(path); 28 if(!file.exists()) 29 file.createNewFile(); 30 FileOutputStream out = new FileOutputStream(file, is_append); //true表示追加 31 StringBuffer sb = new StringBuffer(); 32 sb.append(line + "\n"); 33 out.write(sb.toString().getBytes(encode));// 34 out.close(); 35 } 36 catch(IOException ex) 37 { 38 System.out.println(ex.getStackTrace()); 39 } 40 } 41 42 /** 43 * 写入文件,末尾自动添加\n 44 * @param lines 45 * @param filePath 46 * @param ifContinueWrite 47 */ 48 public static void writeFile(List<String> lines, String filePath, boolean ifContinueWrite){ 49 try{ 50 BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, ifContinueWrite)); 51 for(String line : lines){ 52 bw.write(line+"\n"); 53 } 54 bw.close(); 55 }catch(Exception e){ 56 e.printStackTrace(); 57 } 58 } 59 60 61 /** 62 * 加入编码 63 * 整个文件以string放回,添加\n换行 64 * @param path 65 * @return 66 */ 67 public static String readLogByStringAndEncode(String path, String encode) 68 { 69 StringBuffer sb=new StringBuffer(); 70 String tempstr=null; 71 try { 72 File file=new File(path); 73 if(!file.exists()) 74 throw new FileNotFoundException(); 75 FileInputStream fis=new FileInputStream(file); 76 BufferedReader br=new BufferedReader(new InputStreamReader(fis, encode)); 77 while((tempstr=br.readLine())!=null) { 78 sb.append(tempstr + "\n"); 79 } 80 } catch(IOException ex) { 81 System.out.println(ex.getStackTrace()); 82 } 83 return sb.toString(); 84 } 85 86 /** 87 * 按行读取文件,以list<String>的形式返回 88 * @param filePath 89 * @return 90 */ 91 public static List<String> readLogByList(String filePath){ 92 List<String> lines = new ArrayList<String>(); 93 try { 94 BufferedReader br = new BufferedReader(new FileReader(filePath)); 95 String line = null; 96 while( (line = br.readLine()) != null ){ 97 lines.add(line); 98 } 99 br.close(); 100 }catch(Exception e){ 101 e.printStackTrace(); 102 }finally { 103 return lines; 104 } 105 } 106 107 }