当前位置: 首页 > news >正文

FileToolkit 文件工具箱

  1 import org.apache.commons.io.FileUtils; 
  2 import org.apache.commons.io.filefilter.*; 
  3 import org.apache.commons.logging.Log; 
  4 import org.apache.commons.logging.LogFactory;
  5 
  6 import java.io.*;
  7 
  8 /** 
  9 * 文件工具箱 
 10 * 
 11 * @author leizhimin 2008-12-15 13:59:16 
 12 */ 
 13 public final class FileToolkit { 
 14         private static final Log log = LogFactory.getLog(FileToolkit.class);
 15 
 16         /** 
 17          * 复制文件或者目录,复制前后文件完全一样。 
 18          * 
 19          * @param resFilePath 源文件路径 
 20          * @param distFolder    目标文件夹 
 21          * @IOException 当操作发生异常时抛出 
 22          */ 
 23         public static void copyFile(String resFilePath, String distFolder) throws IOException { 
 24                 File resFile = new File(resFilePath); 
 25                 File distFile = new File(distFolder); 
 26                 if (resFile.isDirectory()) { 
 27                         FileUtils.copyDirectoryToDirectory(resFile, distFile); 
 28                 } else if (resFile.isFile()) { 
 29                         FileUtils.copyFileToDirectory(resFile, distFile, true); 
 30                 } 
 31         }
 32 
 33         /** 
 34          * 删除一个文件或者目录 
 35          * 
 36          * @param targetPath 文件或者目录路径 
 37          * @IOException 当操作发生异常时抛出 
 38          */ 
 39         public static void deleteFile(String targetPath) throws IOException { 
 40                 File targetFile = new File(targetPath); 
 41                 if (targetFile.isDirectory()) { 
 42                         FileUtils.deleteDirectory(targetFile); 
 43                 } else if (targetFile.isFile()) { 
 44                         targetFile.delete(); 
 45                 } 
 46         }
 47 
 48         /** 
 49          * 移动文件或者目录,移动前后文件完全一样,如果目标文件夹不存在则创建。 
 50          * 
 51          * @param resFilePath 源文件路径 
 52          * @param distFolder    目标文件夹 
 53          * @IOException 当操作发生异常时抛出 
 54          */ 
 55         public static void moveFile(String resFilePath, String distFolder) throws IOException { 
 56                 File resFile = new File(resFilePath); 
 57                 File distFile = new File(distFolder); 
 58                 if (resFile.isDirectory()) { 
 59                         FileUtils.moveDirectoryToDirectory(resFile, distFile, true); 
 60                 } else if (resFile.isFile()) { 
 61                         FileUtils.moveFileToDirectory(resFile, distFile, true); 
 62                 } 
 63         }
 64 
 65 
 66         /** 
 67          * 重命名文件或文件夹 
 68          * 
 69          * @param resFilePath 源文件路径 
 70          * @param newFileName 重命名 
 71          * @return 操作成功标识 
 72          */ 
 73         public static boolean renameFile(String resFilePath, String newFileName) { 
 74                 String newFilePath = StringToolkit.formatPath(StringToolkit.getParentPath(resFilePath) + "/" + newFileName); 
 75                 File resFile = new File(resFilePath); 
 76                 File newFile = new File(newFilePath); 
 77                 return resFile.renameTo(newFile); 
 78         }
 79 
 80         /** 
 81          * 读取文件或者目录的大小 
 82          * 
 83          * @param distFilePath 目标文件或者文件夹 
 84          * @return 文件或者目录的大小,如果获取失败,则返回-1 
 85          */ 
 86         public static long genFileSize(String distFilePath) { 
 87                 File distFile = new File(distFilePath); 
 88                 if (distFile.isFile()) { 
 89                         return distFile.length(); 
 90                 } else if (distFile.isDirectory()) { 
 91                         return FileUtils.sizeOfDirectory(distFile); 
 92                 } 
 93                 return -1L; 
 94         }
 95 
 96         /** 
 97          * 判断一个文件是否存在 
 98          * 
 99          * @param filePath 文件路径 
100          * @return 存在返回true,否则返回false 
101          */ 
102         public static boolean isExist(String filePath) { 
103                 return new File(filePath).exists(); 
104         }
105 
106         /** 
107          * 本地某个目录下的文件列表(不递归) 
108          * 
109          * @param folder ftp上的某个目录 
110          * @param suffix 文件的后缀名(比如.mov.xml) 
111          * @return 文件名称列表 
112          */ 
113         public static String[] listFilebySuffix(String folder, String suffix) { 
114                 IOFileFilter fileFilter1 = new SuffixFileFilter(suffix); 
115                 IOFileFilter fileFilter2 = new NotFileFilter(DirectoryFileFilter.INSTANCE); 
116                 FilenameFilter filenameFilter = new AndFileFilter(fileFilter1, fileFilter2); 
117                 return new File(folder).list(filenameFilter); 
118         }
119 
120         /** 
121          * 将字符串写入指定文件(当指定的父路径中文件夹不存在时,会最大限度去创建,以保证保存成功!) 
122          * 
123          * @param res            原字符串 
124          * @param filePath 文件路径 
125          * @return 成功标记 
126          */ 
127         public static boolean string2File(String res, String filePath) { 
128                 boolean flag = true; 
129                 BufferedReader bufferedReader = null; 
130                 BufferedWriter bufferedWriter = null; 
131                 try { 
132                         File distFile = new File(filePath); 
133                         if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs(); 
134                         bufferedReader = new BufferedReader(new StringReader(res)); 
135                         bufferedWriter = new BufferedWriter(new FileWriter(distFile)); 
136                         char buf[] = new char[1024];         //字符缓冲区 
137                         int len; 
138                         while ((len = bufferedReader.read(buf)) != -1) { 
139                                 bufferedWriter.write(buf, 0, len); 
140                         } 
141                         bufferedWriter.flush(); 
142                         bufferedReader.close(); 
143                         bufferedWriter.close(); 
144                 } catch (IOException e) { 
145                         flag = false; 
146                         e.printStackTrace(); 
147                 } 
148                 return flag; 
149         } 
150 } 
151 -------------------------------------------------------------------------------------------------------------
152 import java.io.File;
153 import java.util.ArrayList;
154 import java.util.List;
155 import java.util.Properties;
156 
157 
158 /**
159 * 字符串工具箱
160 *
161 * @author leizhimin 2008-12-15 22:40:12
162 */
163 public final class StringToolkit {
164   /**
165   * 将一个字符串的首字母改为大写或者小写
166   *
167   * @param srcString 源字符串
168   * @param flag     大小写标识,ture小写,false大些
169   * @return 改写后的新字符串
170   */
171   public static String toLowerCaseInitial(String srcString, boolean flag) {
172     StringBuilder sb = new StringBuilder();
173     if (flag) {
174         sb.append(Character.toLowerCase(srcString.charAt(0)));
175     } else {
176         sb.append(Character.toUpperCase(srcString.charAt(0)));
177     }
178     sb.append(srcString.substring(1));
179     return sb.toString();
180   }
181 
182   /**
183   * 将一个字符串按照句点(.)分隔,返回最后一段
184   *
185   * @param clazzName 源字符串
186   * @return 句点(.)分隔后的最后一段字符串
187   */
188   public static String getLastName(String clazzName) {
189     String[] ls = clazzName.split("\\.");
190     return ls[ls.length - 1];
191   }
192 
193   /**
194   * 格式化文件路径,将其中不规范的分隔转换为标准的分隔符,并且去掉末尾的"/"符号。
195   *
196   * @param path 文件路径
197   * @return 格式化后的文件路径
198   */
199   public static String formatPath(String path) {
200     String reg0 = "\\\\+";
201     String reg = "\\\\+|/+";
202     String temp = path.trim().replaceAll(reg0, "/");
203     temp = temp.replaceAll(reg, "/");
204     if (temp.endsWith("/")) {
205         temp = temp.substring(0, temp.length() - 1);
206     }
207     if (System.getProperty("file.separator").equals("\\")) {
208       temp= temp.replace('/','\\');
209     }
210     return temp;
211   }
212 
213   /**
214   * 格式化文件路径,将其中不规范的分隔转换为标准的分隔符,并且去掉末尾的"/"符号(适用于FTP远程文件路径或者Web资源的相对路径)。
215   *
216   * @param path 文件路径
217   * @return 格式化后的文件路径
218   */
219   public static String formatPath4Ftp(String path) {
220     String reg0 = "\\\\+";
221     String reg = "\\\\+|/+";
222     String temp = path.trim().replaceAll(reg0, "/");
223     temp = temp.replaceAll(reg, "/");
224     if (temp.endsWith("/")) {
225         temp = temp.substring(0, temp.length() - 1);
226     }
227     return temp;
228   }
229 
230   public static void main(String[] args) {
231     System.out.println(System.getProperty("file.separator"));
232     Properties p = System.getProperties();
233     System.out.println(formatPath("C:///\\xxxx\\\\\\\\\\///\\\\R5555555.txt"));
234 
235 //     List<String> result = series2List("asdf | sdf|siii|sapp|aaat| ", "\\|");
236 //     System.out.println(result.size());
237 //     for (String s : result) {
238 //         System.out.println(s);
239 //     }
240   }
241 
242   /**
243   * 获取文件父路径
244   *
245   * @param path 文件路径
246   * @return 文件父路径
247   */
248   public static String getParentPath(String path) {
249     return new File(path).getParent();
250   }
251 
252   /**
253   * 获取相对路径
254   *
255   * @param fullPath 全路径
256   * @param rootPath 根路径
257   * @return 相对根路径的相对路径
258   */
259   public static String getRelativeRootPath(String fullPath, String rootPath) {
260     String relativeRootPath = null;
261     String _fullPath = formatPath(fullPath);
262     String _rootPath = formatPath(rootPath);
263 
264     if (_fullPath.startsWith(_rootPath)) {
265         relativeRootPath = fullPath.substring(_rootPath.length());
266     } else {
267         throw new RuntimeException("要处理的两个字符串没有包含关系,处理失败!");
268     }
269     if (relativeRootPath == null) return null;
270     else
271         return formatPath(relativeRootPath);
272   }
273 
274   /**
275   * 获取当前系统换行符
276   *
277   * @return 系统换行符
278   */
279   public static String getSystemLineSeparator() {
280     return System.getProperty("line.separator");
281   }
282 
283   /**
284   * 将用“|”分隔的字符串转换为字符串集合列表,剔除分隔后各个字符串前后的空格
285   *
286   * @param series 将用“|”分隔的字符串
287   * @return 字符串集合列表
288   */
289   public static List<String> series2List(String series) {
290     return series2List(series, "\\|");
291   }
292 
293   /**
294   * 将用正则表达式regex分隔的字符串转换为字符串集合列表,剔除分隔后各个字符串前后的空格
295   *
296   * @param series 用正则表达式分隔的字符串
297   * @param regex 分隔串联串的正则表达式
298   * @return 字符串集合列表
299   */
300   private static List<String> series2List(String series, String regex) {
301     List<String> result = new ArrayList<String>();
302     if (series != null && regex != null) {
303         for (String s : series.split(regex)) {
304           if (s.trim() != null && !s.trim().equals("")) result.add(s.trim());
305         }
306     }
307     return result;
308   }
309 
310   /**
311   * @param strList 字符串集合列表
312   * @return 通过“|”串联为一个字符串
313   */
314   public static String list2series(List<String> strList) {
315     StringBuffer series = new StringBuffer();
316     for (String s : strList) {
317         series.append(s).append("|");
318     }
319     return series.toString();
320   }
321 
322   /**
323   * 将字符串的首字母转为小写
324   *
325   * @param resStr 源字符串
326   * @return 首字母转为小写后的字符串
327   */
328   public static String firstToLowerCase(String resStr) {
329     if (resStr == null) {
330         return null;
331     } else if ("".equals(resStr.trim())) {
332         return "";
333     } else {
334         StringBuffer sb = new StringBuffer();
335         Character c = resStr.charAt(0);
336         if (Character.isLetter(c)) {
337           if (Character.isUpperCase(c))
338             c = Character.toLowerCase(c);
339           sb.append(resStr);
340           sb.setCharAt(0, c);
341           return sb.toString();
342         }
343     }
344     return resStr;
345   }
346 
347   /**
348   * 将字符串的首字母转为大写
349   *
350   * @param resStr 源字符串
351   * @return 首字母转为大写后的字符串
352   */
353   public static String firstToUpperCase(String resStr) {
354     if (resStr == null) {
355         return null;
356     } else if ("".equals(resStr.trim())) {
357         return "";
358     } else {
359         StringBuffer sb = new StringBuffer();
360         Character c = resStr.charAt(0);
361         if (Character.isLetter(c)) {
362           if (Character.isLowerCase(c))
363             c = Character.toUpperCase(c);
364           sb.append(resStr);
365           sb.setCharAt(0, c);
366           return sb.toString();
367         }
368     }
369     return resStr;
370   }
371 
372 }

 

相关文章:

  • 解决数据架构难点数据分布的六种策略
  • Linux系统——提高编译速度的方法
  • 视频播放插件Video.js
  • Android Studio安装配置
  • WebApi接口 - 如何在应用中调用webapi接口
  • 管理两个字
  • Linux基础2
  • python 调用 zabbixApi
  • less 转栏
  • 行列式计算的两种方法
  • Android源码解析--超好看的下拉刷新动画
  • ES6核心内容精讲--快速实践ES6(二)
  • C++——编程常见错误
  • linux -硬盘分区
  • [8-27]正则表达式、扩展表达式以及相关实战
  • C# 免费离线人脸识别 2.0 Demo
  • CSS魔法堂:Absolute Positioning就这个样
  • docker容器内的网络抓包
  • happypack两次报错的问题
  • iOS筛选菜单、分段选择器、导航栏、悬浮窗、转场动画、启动视频等源码
  • Java面向对象及其三大特征
  • PHP变量
  • 动态规划入门(以爬楼梯为例)
  • 简单数学运算程序(不定期更新)
  • 前端_面试
  • 微信小程序:实现悬浮返回和分享按钮
  • AI算硅基生命吗,为什么?
  • !! 2.对十份论文和报告中的关于OpenCV和Android NDK开发的总结
  • #NOIP 2014# day.1 T2 联合权值
  • #NOIP 2014# day.1 生活大爆炸版 石头剪刀布
  • #我与Java虚拟机的故事#连载01:人在JVM,身不由己
  • (Java岗)秋招打卡!一本学历拿下美团、阿里、快手、米哈游offer
  • (第61天)多租户架构(CDB/PDB)
  • (动手学习深度学习)第13章 计算机视觉---图像增广与微调
  • (解决办法)ASP.NET导出Excel,打开时提示“您尝试打开文件'XXX.xls'的格式与文件扩展名指定文件不一致
  • (九)One-Wire总线-DS18B20
  • (全部习题答案)研究生英语读写教程基础级教师用书PDF|| 研究生英语读写教程提高级教师用书PDF
  • (三)模仿学习-Action数据的模仿
  • .NET Core 网络数据采集 -- 使用AngleSharp做html解析
  • .NET Micro Framework初体验(二)
  • .net 按比例显示图片的缩略图
  • .NET/C# 中设置当发生某个特定异常时进入断点(不借助 Visual Studio 的纯代码实现)
  • .Net6 Api Swagger配置
  • .Net程序猿乐Android发展---(10)框架布局FrameLayout
  • .NET简谈互操作(五:基础知识之Dynamic平台调用)
  • .net网站发布-允许更新此预编译站点
  • .NET序列化 serializable,反序列化
  • [ 隧道技术 ] cpolar 工具详解之将内网端口映射到公网
  • [100天算法】-实现 strStr()(day 52)
  • [C#]C#学习笔记-CIL和动态程序集
  • [C++]拼图游戏
  • [codevs] 1029 遍历问题
  • [Go WebSocket] 多房间的聊天室(五)用多个小锁代替大锁,提高效率
  • [java后端研发]——文件上传与下载(2种方式)
  • [Luogu P3527BZOJ 2527][Poi2011]Meteors(整体二分+BIT)