23 遍历删除本地目录的方法,文件末尾追加内容,按行读取文件内容
1、遍历删除本地目录
/** * 递归删除非空目录 * @param file */ public static void deletNotEmptyDir(File file){ File[] files = file.listFiles(); if (files != null) { for (File f : files) { deletNotEmptyDir(f); } } file.delete(); }
2、文件末尾追加内容
/** * 在文件末尾追加字符串 * @param filePath * @param appendStr * @return */ public static Boolean appendStringToFile(String filePath,String appendStr){ Boolean sucess=true; if(!new File(filePath).exists()){ LOG.error("文件:{}不存在",filePath); return false; } FileWriter writer=null; try { writer=new FileWriter(filePath,true); writer.write("\n"+appendStr); } catch (IOException e) { sucess=false; e.printStackTrace(); }finally { if(null!=writer){ try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } return sucess; }
3、按行读取文件内容
/** * 把文件内容一行一行放到list里面 * @return */ public static List<String> resolveFileByLine(String filePath){ List<String> list=new ArrayList<>(); BufferedReader bufferedReader=null; try { bufferedReader=new BufferedReader(new FileReader(filePath)); String line=null; while (null!=(line=bufferedReader.readLine())){ list.add(line.trim()); } } catch (FileNotFoundException e) { LOG.error("未发现文件:{}",filePath); e.printStackTrace(); } catch (IOException e) { LOG.error("读取文件:{} 异常,异常信息:{}",filePath,e.getMessage()); e.printStackTrace(); }finally { if(null!=bufferedReader){ try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } return list; }
本文来自博客园,作者:life_start,转载请注明原文链接:https://www.cnblogs.com/yangh2016/p/6076948.html