|
| 1 | +package tech.sqlclub.common.utils |
| 2 | + |
| 3 | +import java.io.{File, FileInputStream, InputStream} |
| 4 | +import java.util.Properties |
| 5 | + |
| 6 | +import org.apache.commons.lang3.StringUtils |
| 7 | +import org.yaml.snakeyaml.Yaml |
| 8 | +import tech.sqlclub.common.regex.RegexOp._ |
| 9 | +import scala.collection.JavaConversions._ |
| 10 | + |
| 11 | +/** |
| 12 | + * |
| 13 | + * Created by songgr on 2020/01/03. |
| 14 | + */ |
| 15 | +object FileUtils { |
| 16 | + |
| 17 | + /** |
| 18 | + * 获取目录文件列表 |
| 19 | + * @param path 目录 |
| 20 | + * @param pattern 匹配正则 |
| 21 | + * @param recursive 是否递归子目录 |
| 22 | + * @return Array[File] |
| 23 | + */ |
| 24 | + def lsfile(path:String, pattern:String = ".*", recursive:Boolean=false):Array[File] = { |
| 25 | + |
| 26 | + val file = new File(path) |
| 27 | + |
| 28 | + if (file.isDirectory){ |
| 29 | + |
| 30 | + val files = file.listFiles().filter(_.isFile).filter(_.getName matching pattern ) |
| 31 | + |
| 32 | + if (recursive) { |
| 33 | + val fs = file.listFiles().filter(_.isDirectory).flatMap{ |
| 34 | + f => |
| 35 | + lsfile(f.getAbsolutePath, pattern, recursive) |
| 36 | + } |
| 37 | + return files ++ fs |
| 38 | + } |
| 39 | + return files |
| 40 | + } |
| 41 | + Array.empty[File] |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + /** |
| 46 | + * 创建目录 |
| 47 | + * @param path 目录 |
| 48 | + * @return Boolean |
| 49 | + */ |
| 50 | + def mkdirs(path:String): Boolean = { |
| 51 | + if (StringUtils.isNotBlank(path)) { |
| 52 | + val file = new File(path) |
| 53 | + if (!file.isDirectory){ |
| 54 | + if (!file.exists) file.mkdirs() |
| 55 | + } |
| 56 | + } |
| 57 | + false |
| 58 | + } |
| 59 | + |
| 60 | + def readYamlFile(path:String):Map[String,Object] = readYamlFile(new File(path)) |
| 61 | + |
| 62 | + def readYamlFile(file:File) |
| 63 | + (implicit inputStream:InputStream=new FileInputStream(file)):Map[String,Object] = { |
| 64 | + try { |
| 65 | + val yaml = new Yaml() |
| 66 | + yaml.load[java.util.Map[String,Object]](inputStream).toMap |
| 67 | + } finally { |
| 68 | + inputStream.close() |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + |
| 73 | + def readPropertiesFile(path:String):Map[String,Object] = readPropertiesFile(new File(path)) |
| 74 | + |
| 75 | + def readPropertiesFile(file:File) |
| 76 | + (implicit inputStream:InputStream=new FileInputStream(file)):Map[String,Object] = { |
| 77 | + try { |
| 78 | + val properties = new Properties() |
| 79 | + properties.load(inputStream) |
| 80 | + properties.toMap[String,Object] |
| 81 | + } finally { |
| 82 | + inputStream.close() |
| 83 | + |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | +} |
0 commit comments