描述:文件操作帮助类 作者:蒋庆意 日期时间:2021/1/18 11:27 cocoasjiang@foxmail.com
| 13 | * cocoasjiang@foxmail.com |
| 14 | */ |
| 15 | public class FileUtils { |
| 16 | |
| 17 | /** |
| 18 | * 获取文件名 |
| 19 | * @param filePath 文件路径 |
| 20 | * @return |
| 21 | */ |
| 22 | public static String getFileName(String filePath){ |
| 23 | if(null == filePath || new File(filePath).isDirectory()){ |
| 24 | return ""; |
| 25 | } |
| 26 | File file = new File(filePath); |
| 27 | return file.getName(); |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * 判断文件是否符合指定的文件类型 |
| 32 | * @param f |
| 33 | * @param fileTypes |
| 34 | * @return |
| 35 | */ |
| 36 | public static boolean matchFile(File f, List<String> fileTypes){ |
| 37 | if(f == null || f.isDirectory()){ |
| 38 | return false; |
| 39 | } |
| 40 | for(String fileType : fileTypes){ |
| 41 | if(f.getAbsolutePath().endsWith(fileType)){ |
| 42 | return true; |
| 43 | } |
| 44 | } |
| 45 | return false; |
| 46 | } |
| 47 | |
| 48 | |
| 49 | /** |
| 50 | * 按行读取文件内容:过滤空行和注释 |
| 51 | * @param filePath |
| 52 | * @return |
| 53 | */ |
| 54 | public static List<String> readFile(String filePath){ |
| 55 | if(null == filePath || new File(filePath).isDirectory()){ |
| 56 | return new ArrayList<>(); |
| 57 | } |
| 58 | List<String> lines = new ArrayList<>(); |
| 59 | try { |
| 60 | BufferedReader reader = new BufferedReader(new FileReader(new File(filePath))); |
| 61 | String line = reader.readLine(); |
| 62 | while(null != line){ |
| 63 | if(filterLine(line)){// 过滤不符合要求的代码行 |
| 64 | lines.add(line); |
| 65 | } |
| 66 | line = reader.readLine(); |
| 67 | } |
| 68 | return lines; |
| 69 | } catch (FileNotFoundException e) { |
| 70 | LogUtils.error("读取文件<" + filePath + ">出错:" + e.getMessage()); |
| 71 | } catch (IOException e) { |
| 72 | LogUtils.error("读取文件<" + filePath + ">出错:" + e.getMessage()); |
nothing calls this directly
no outgoing calls
no test coverage detected