1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileReader;
  7. import java.io.FileWriter;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.io.OutputStream;
  12. import java.io.PrintWriter;
  13. import java.net.URLEncoder;
  14. import java.util.ArrayList;
  15. import java.util.Calendar;
  16. import java.util.Date;
  17. import java.util.HashMap;
  18. import java.util.HashSet;
  19. import java.util.List;
  20.  
  21. import javax.servlet.http.HttpServletResponse;
  22.  
  23. /**
  24. * <p>文件操作工具类<p>
  25. * @version 1.0
  26. * @author li_hao
  27. * @date 2017年1月18日
  28. */
  29. @SuppressWarnings({"resource","unused"})
  30. public class FileUtils {
  31.  
  32. /**
  33. * 获取windows/linux的项目根目录
  34. * @return
  35. */
  36. public static String getConTextPath(){
  37. String fileUrl = Thread.currentThread().getContextClassLoader().getResource("").getPath();
  38. if("usr".equals(fileUrl.substring(,))){
  39. fileUrl = (fileUrl.substring(,fileUrl.length()-));//linux
  40. }else{
  41. fileUrl = (fileUrl.substring(,fileUrl.length()-));//windows
  42. }
  43. return fileUrl;
  44. }
  45.  
  46. /**
  47. * 字符串转数组
  48. * @param str 字符串
  49. * @param splitStr 分隔符
  50. * @return
  51. */
  52. public static String[] StringToArray(String str,String splitStr){
  53. String[] arrayStr = null;
  54. if(!"".equals(str) && str != null){
  55. if(str.indexOf(splitStr)!=-){
  56. arrayStr = str.split(splitStr);
  57. }else{
  58. arrayStr = new String[];
  59. arrayStr[] = str;
  60. }
  61. }
  62. return arrayStr;
  63. }
  64.  
  65. /**
  66. * 读取文件
  67. *
  68. * @param Path
  69. * @return
  70. */
  71. public static String ReadFile(String Path) {
  72. BufferedReader reader = null;
  73. String laststr = "";
  74. try {
  75. FileInputStream fileInputStream = new FileInputStream(Path);
  76. InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
  77. reader = new BufferedReader(inputStreamReader);
  78. String tempString = null;
  79. while ((tempString = reader.readLine()) != null) {
  80. laststr += tempString;
  81. }
  82. reader.close();
  83. } catch (IOException e) {
  84. e.printStackTrace();
  85. } finally {
  86. if (reader != null) {
  87. try {
  88. reader.close();
  89. } catch (IOException e) {
  90. e.printStackTrace();
  91. }
  92. }
  93. }
  94. return laststr;
  95. }
  96.  
  97. /**
  98. * 获取文件夹下所有文件的名称 + 模糊查询(当不需要模糊查询时,queryStr传空或null即可)
  99. * 1.当路径不存在时,map返回retType值为1
  100. * 2.当路径为文件路径时,map返回retType值为2,文件名fileName值为文件名
  101. * 3.当路径下有文件夹时,map返回retType值为3,文件名列表fileNameList,文件夹名列表folderNameList
  102. * @param folderPath 路径
  103. * @param queryStr 模糊查询字符串
  104. * @return
  105. */
  106. public static HashMap<String, Object> getFilesName(String folderPath , String queryStr) {
  107. HashMap<String, Object> map = new HashMap<>();
  108. List<String> fileNameList = new ArrayList<>();//文件名列表
  109. List<String> folderNameList = new ArrayList<>();//文件夹名列表
  110. File f = new File(folderPath);
  111. if (!f.exists()) { //路径不存在
  112. map.put("retType", "");
  113. }else{
  114. boolean flag = f.isDirectory();
  115. if(flag==false){ //路径为文件
  116. map.put("retType", "");
  117. map.put("fileName", f.getName());
  118. }else{ //路径为文件夹
  119. map.put("retType", "");
  120. File fa[] = f.listFiles();
  121. queryStr = queryStr==null ? "" : queryStr;//若queryStr传入为null,则替换为空(indexOf匹配值不能为null)
  122. for (int i = ; i < fa.length; i++) {
  123. File fs = fa[i];
  124. if(fs.getName().indexOf(queryStr)!=-){
  125. if (fs.isDirectory()) {
  126. folderNameList.add(fs.getName());
  127. } else {
  128. fileNameList.add(fs.getName());
  129. }
  130. }
  131. }
  132. map.put("fileNameList", fileNameList);
  133. map.put("folderNameList", folderNameList);
  134. }
  135. }
  136. return map;
  137. }
  138.  
  139. /**
  140. * 以行为单位读取文件,读取到最后一行
  141. * @param filePath
  142. * @return
  143. */
  144. public static List<String> readFileContent(String filePath) {
  145. BufferedReader reader = null;
  146. List<String> listContent = new ArrayList<>();
  147. try {
  148. reader = new BufferedReader(new FileReader(filePath));
  149. String tempString = null;
  150. int line = ;
  151. // 一次读入一行,直到读入null为文件结束
  152. while ((tempString = reader.readLine()) != null) {
  153. listContent.add(tempString);
  154. line++;
  155. }
  156. reader.close();
  157. } catch (IOException e) {
  158. e.printStackTrace();
  159. } finally {
  160. if (reader != null) {
  161. try {
  162. reader.close();
  163. } catch (IOException e1) {
  164. }
  165. }
  166. }
  167. return listContent;
  168. }
  169.  
  170. /**
  171. * 读取指定行数据 ,注意:0为开始行
  172. * @param filePath
  173. * @param lineNumber
  174. * @return
  175. */
  176. public static String readLineContent(String filePath,int lineNumber){
  177. BufferedReader reader = null;
  178. String lineContent="";
  179. try {
  180. reader = new BufferedReader(new FileReader(filePath));
  181. int line=;
  182. while(line<=lineNumber){
  183. lineContent=reader.readLine();
  184. line++;
  185. }
  186. reader.close();
  187. } catch (IOException e) {
  188. e.printStackTrace();
  189. } finally {
  190. if (reader != null) {
  191. try {
  192. reader.close();
  193. } catch (IOException e1) {
  194. }
  195. }
  196. }
  197. return lineContent;
  198. }
  199.  
  200. /**
  201. * 读取从beginLine到endLine数据(包含beginLine和endLine),注意:0为开始行
  202. * @param filePath
  203. * @param beginLineNumber 开始行
  204. * @param endLineNumber 结束行
  205. * @return
  206. */
  207. public static List<String> readLinesContent(String filePath,int beginLineNumber,int endLineNumber){
  208. List<String> listContent = new ArrayList<>();
  209. try{
  210. int count = ;
  211. BufferedReader reader = new BufferedReader(new FileReader(filePath));
  212. String content = reader.readLine();
  213. while(content !=null){
  214. if(count >= beginLineNumber && count <=endLineNumber){
  215. listContent.add(content);
  216. }
  217. content = reader.readLine();
  218. count++;
  219. }
  220. } catch(Exception e){
  221. }
  222. return listContent;
  223. }
  224.  
  225. /**
  226. * 读取若干文件中所有数据
  227. * @param listFilePath
  228. * @return
  229. */
  230. public static List<String> readFileContent_list(List<String> listFilePath) {
  231. List<String> listContent = new ArrayList<>();
  232. for(String filePath : listFilePath){
  233. File file = new File(filePath);
  234. BufferedReader reader = null;
  235. try {
  236. reader = new BufferedReader(new FileReader(file));
  237. String tempString = null;
  238. int line = ;
  239. // 一次读入一行,直到读入null为文件结束
  240. while ((tempString = reader.readLine()) != null) {
  241. listContent.add(tempString);
  242. line++;
  243. }
  244. reader.close();
  245. } catch (IOException e) {
  246. e.printStackTrace();
  247. } finally {
  248. if (reader != null) {
  249. try {
  250. reader.close();
  251. } catch (IOException e1) {
  252. }
  253. }
  254. }
  255. }
  256. return listContent;
  257. }
  258.  
  259. /**
  260. * 文件数据写入(如果文件夹和文件不存在,则先创建,再写入)
  261. * @param filePath
  262. * @param content
  263. * @param flag true:如果文件存在且存在内容,则内容换行追加;false:如果文件存在且存在内容,则内容替换
  264. */
  265. public static String fileLinesWrite(String filePath,String content,boolean flag){
  266. String filedo = "write";
  267. FileWriter fw = null;
  268. try {
  269. File file=new File(filePath);
  270. //如果文件夹不存在,则创建文件夹
  271. if (!file.getParentFile().exists()){
  272. file.getParentFile().mkdirs();
  273. }
  274. if(!file.exists()){//如果文件不存在,则创建文件,写入第一行内容
  275. file.createNewFile();
  276. fw = new FileWriter(file);
  277. filedo = "create";
  278. }else{//如果文件存在,则追加或替换内容
  279. fw = new FileWriter(file, flag);
  280. }
  281. } catch (IOException e) {
  282. e.printStackTrace();
  283. }
  284. PrintWriter pw = new PrintWriter(fw);
  285. pw.println(content);
  286. pw.flush();
  287. try {
  288. fw.flush();
  289. pw.close();
  290. fw.close();
  291. } catch (IOException e) {
  292. e.printStackTrace();
  293. }
  294. return filedo;
  295. }
  296.  
  297. /**
  298. * 写文件
  299. * @param ins
  300. * @param out
  301. */
  302. public static void writeIntoOut(InputStream ins, OutputStream out) {
  303. byte[] bb = new byte[ * ];
  304. try {
  305. int cnt = ins.read(bb);
  306. while (cnt > ) {
  307. out.write(bb, , cnt);
  308. cnt = ins.read(bb);
  309. }
  310. } catch (IOException e) {
  311. e.printStackTrace();
  312. } finally {
  313. try {
  314. out.flush();
  315. ins.close();
  316. out.close();
  317. } catch (IOException e) {
  318. e.printStackTrace();
  319. }
  320. }
  321. }
  322.  
  323. /**
  324. * 判断list中元素是否完全相同(完全相同返回true,否则返回false)
  325. * @param list
  326. * @return
  327. */
  328. private static boolean hasSame(List<? extends Object> list){
  329. if(null == list)
  330. return false;
  331. return == new HashSet<Object>(list).size();
  332. }
  333.  
  334. /**
  335. * 判断list中是否有重复元素(无重复返回true,否则返回false)
  336. * @param list
  337. * @return
  338. */
  339. private static boolean hasSame2(List<? extends Object> list){
  340. if(null == list)
  341. return false;
  342. return list.size() == new HashSet<Object>(list).size();
  343. }
  344.  
  345. /**
  346. * 增加/减少天数
  347. * @param date
  348. * @param num
  349. * @return
  350. */
  351. public static Date DateAddOrSub(Date date, int num) {
  352. Calendar startDT = Calendar.getInstance();
  353. startDT.setTime(date);
  354. startDT.add(Calendar.DAY_OF_MONTH, num);
  355. return startDT.getTime();
  356. }
  357.  
  358. }

java简单的文件读写工具类的更多相关文章

  1. properties文件读写工具类

    java代码: import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; ...

  2. Spring-Boot ☞ ShapeFile文件读写工具类+接口调用

    一.项目目录结构树 二.项目启动 三.往指定的shp文件里写内容 (1) json数据[Post] { "name":"test", "path&qu ...

  3. android 文件读写工具类

    将可以序列化的对象通过base64编码后进行保存 但是感觉多数情况下,不需要采用这个功能,直接保存原始的json字符串,取出来之后再进行解析即可 package com.wotlab.home.mon ...

  4. list集合、txt文件对比的工具类和文件读写工具类

    工作上经常会遇到处理大数据的问题,下面两个工具类,是在处理大数据时编写的:推荐的是使用map的方式处理两个list数据,如果遇到list相当大数据这个方法就起到了作用,当时处理了两个十万级的list, ...

  5. java文件读写工具类

    依赖jar:commons-io.jar 1.写文件 // by FileUtilsList<String> lines = FileUtils.readLines(file, " ...

  6. Java操作属性文件之工具类

    最近空闲时间整理一下平时常用的一下工具类,重复造轮子实在是浪费时间,如果不正确或者有待改善的地方,欢迎指教... package com.hsuchan.business.utils; import ...

  7. properties文件读写工具类PropertiesUtil.java

    import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import ...

  8. java IO Nio 文件拷贝工具类Files

    public static void main(String[] args) throws Exception { Files.copy(Paths.get("file/text.txt&q ...

  9. 文件类型工具类:FileTypeUtil

    个人学习,仅供参考! package com.example.administrator.filemanager.utils;import java.io.File;/** * 文件类型工具类 * * ...

随机推荐

  1. jmeter压测、操作数据库、分布式linux下运行、webservice接口测试、charles抓包

    一.jmeter压测 在线程组中设置好,然后添加http请求,t添加聚合报告查看压力测试结果,如图: 一般压测时间10-15分钟,如果是稳定性测试,一般n*12小时,这些并发用户一直在请求. tps: ...

  2. 第二节《Git暂存区》

    在上一节中我们的demo版本库经历了一次提交,我们可以使用git og --stat查看一下提交日志. [root@git demo]# git log --statcommit 986a1bd458 ...

  3. jQuery基础(二)DOM

    DOM节点的创建 jQuery节点创建与属性的处理 创建元素节点: $("<div></div>") 创建为文本节点: $("<div> ...

  4. Fabric的@runs_once的理解

    1:runs_once的用法,一直没理解,我看网上都是说:“函数修饰符,标识的函数只会执行一次,不受多台主机影响”     实在没理解,然后看了一下官方文档,这样解释     举个例子: #!/usr ...

  5. lua tasklib 之lumen 分析

    sched.sleep分析 sleep会填充M.running_task.waitds数据表示当前task需要等待,最后yield出去到主线程 M.sleep = function (timeout) ...

  6. Java 的 volatile 修饰符

    volatile 修饰符,用于多线程同步 volatile 修饰的成员变量在每次被线程访问时,都强制从共享内存中重新读取该成员变量的值.而且,当成员变量发生变化时,会强制线程将变化值回写到共享内存.这 ...

  7. 对数据进行GZIP压缩或解压缩

    /** * 对data进行GZIP解压缩 * @param data * @return * @throws Exception */ public static String unCompress( ...

  8. Linux scp命令详解

    Linux scp命令 Linux scp命令用于Linux之间复制文件和目录. scp是 secure copy的缩写, scp是linux系统下基于ssh登陆进行安全的远程文件拷贝命令. 语法: ...

  9. 在内存中加载DLL

    有个需求是把一个DLL作为数据打包到EXE中,运行的时候动态加载.但要求不是释放出来生成DLL文件加载. 花了一天时间做出来.效果还可以. 不过由于是直接分配内存加载DLL的.有一些小缺陷.例如遍历进 ...

  10. read()、write()返回 Input/output error, Device or resource busy解决

    遇到的问题,通过I2C总线读.写(read.write)fs8816加密芯片,报错如下: read str failed,error= Input/output error! write str fa ...