java 读写文件工具类_JAVA FileUtils(文件读写以及操作工具类)

该文件提供了一系列静态方法,用于处理文件和目录。包括获取项目根目录、字符串转换成数组、读取文件内容、获取文件夹下所有文件名、读取文件的某行内容、读取文件指定行范围的内容、读取多个文件内容、文件数据写入、文件数据追加、文件删除、目录创建、文件是否存在、获取文件后缀名、删除目录及其内容、复制文件等操作。
摘要由CSDN通过智能技术生成

1 packagecom.suning.yypt.business.report;2

3 import java.io.*;4 import java.util.*;5

6 @SuppressWarnings({"resource","unused"})7 public classFileUtils {8

9 /**

10 * 获取windows/linux的项目根目录11 *@return

12 */

13 public staticString getConTextPath(){14 String fileUrl = Thread.currentThread().getContextClassLoader().getResource("").getPath();15 if("usr".equals(fileUrl.substring(1,4))){16 fileUrl = (fileUrl.substring(0,fileUrl.length()-16));//linux

17 }else{18 fileUrl = (fileUrl.substring(1,fileUrl.length()-16));//windows

19 }20 returnfileUrl;21 }22

23 /**

24 * 字符串转数组25 *@paramstr 字符串26 *@paramsplitStr 分隔符27 *@return

28 */

29 public staticString[] StringToArray(String str,String splitStr){30 String[] arrayStr = null;31 if(!"".equals(str) && str != null){32 if(str.indexOf(splitStr)!=-1){33 arrayStr =str.split(splitStr);34 }else{35 arrayStr = new String[1];36 arrayStr[0] =str;37 }38 }39 returnarrayStr;40 }41

42 /**

43 * 读取文件44 *45 *@paramPath46 *@return

47 */

48 public staticString ReadFile(String Path) {49 BufferedReader reader = null;50 String laststr = "";51 try{52 FileInputStream fileInputStream = newFileInputStream(Path);53 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");54 reader = newBufferedReader(inputStreamReader);55 String tempString = null;56 while ((tempString = reader.readLine()) != null) {57 laststr +=tempString;58 }59 reader.close();60 } catch(IOException e) {61 e.printStackTrace();62 } finally{63 if (reader != null) {64 try{65 reader.close();66 } catch(IOException e) {67 e.printStackTrace();68 }69 }70 }71 returnlaststr;72 }73

74 /**

75 * 获取文件夹下所有文件的名称 + 模糊查询(当不需要模糊查询时,queryStr传空或null即可)76 * 1.当路径不存在时,map返回retType值为177 * 2.当路径为文件路径时,map返回retType值为2,文件名fileName值为文件名78 * 3.当路径下有文件夹时,map返回retType值为3,文件名列表fileNameList,文件夹名列表folderNameList79 *@paramfolderPath 路径80 *@paramqueryStr 模糊查询字符串81 *@return

82 */

83 public static HashMapgetFilesName(String folderPath , String queryStr) {84 HashMap map = new HashMap<>();85 List fileNameList = new ArrayList<>();//文件名列表

86 List folderNameList = new ArrayList<>();//文件夹名列表

87 File f = newFile(folderPath);88 if (!f.exists()) { //路径不存在

89 map.put("retType", "1");90 }else{91 boolean flag =f.isDirectory();92 if(flag==false){ //路径为文件

93 map.put("retType", "2");94 map.put("fileName", f.getName());95 }else{ //路径为文件夹

96 map.put("retType", "3");97 File fa[] =f.listFiles();98 queryStr = queryStr==null ? "" : queryStr;//若queryStr传入为null,则替换为空(indexOf匹配值不能为null)

99 for (int i = 0; i < fa.length; i++) {100 File fs =fa[i];101 if(fs.getName().indexOf(queryStr)!=-1){102 if(fs.isDirectory()) {103 folderNameList.add(fs.getName());104 } else{105 fileNameList.add(fs.getName());106 }107 }108 }109 map.put("fileNameList", fileNameList);110 map.put("folderNameList", folderNameList);111 }112 }113 returnmap;114 }115

116 /**

117 * 以行为单位读取文件,读取到最后一行118 *@paramfilePath119 *@return

120 */

121 public static ListreadFileContent(String filePath) {122 BufferedReader reader = null;123 List listContent = new ArrayList<>();124 try{125 reader = new BufferedReader(newFileReader(filePath));126 String tempString = null;127 int line = 1;128 //一次读入一行,直到读入null为文件结束

129 while ((tempString = reader.readLine()) != null) {130 listContent.add(tempString);131 line++;132 }133 reader.close();134 } catch(IOException e) {135 e.printStackTrace();136 } finally{137 if (reader != null) {138 try{139 reader.close();140 } catch(IOException e1) {141 }142 }143 }144 returnlistContent;145 }146

147 /**

148 * 读取指定行数据 ,注意:0为开始行149 *@paramfilePath150 *@paramlineNumber151 *@return

152 */

153 public static String readLineContent(String filePath,intlineNumber){154 BufferedReader reader = null;155 String lineContent="";156 try{157 reader = new BufferedReader(newFileReader(filePath));158 int line=0;159 while(line<=lineNumber){160 lineContent=reader.readLine();161 line++;162 }163 reader.close();164 } catch(IOException e) {165 e.printStackTrace();166 } finally{167 if (reader != null) {168 try{169 reader.close();170 } catch(IOException e1) {171 }172 }173 }174 returnlineContent;175 }176

177 /**

178 * 读取从beginLine到endLine数据(包含beginLine和endLine),注意:0为开始行179 *@paramfilePath180 *@parambeginLineNumber 开始行181 *@paramendLineNumber 结束行182 *@return

183 */

184 public static List readLinesContent(String filePath,int beginLineNumber,intendLineNumber){185 List listContent = new ArrayList<>();186 try{187 int count = 0;188 BufferedReader reader = new BufferedReader(newFileReader(filePath));189 String content =reader.readLine();190 while(content !=null){191 if(count >= beginLineNumber && count <=endLineNumber){192 listContent.add(content);193 }194 content =reader.readLine();195 count++;196 }197 } catch(Exception e){198 }199 returnlistContent;200 }201

202 /**

203 * 读取若干文件中所有数据204 *@paramlistFilePath205 *@return

206 */

207 public static List readFileContent_list(ListlistFilePath) {208 List listContent = new ArrayList<>();209 for(String filePath : listFilePath){210 File file = newFile(filePath);211 BufferedReader reader = null;212 try{213 reader = new BufferedReader(newFileReader(file));214 String tempString = null;215 int line = 1;216 //一次读入一行,直到读入null为文件结束

217 while ((tempString = reader.readLine()) != null) {218 listContent.add(tempString);219 line++;220 }221 reader.close();222 } catch(IOException e) {223 e.printStackTrace();224 } finally{225 if (reader != null) {226 try{227 reader.close();228 } catch(IOException e1) {229 }230 }231 }232 }233 returnlistContent;234 }235

236 /**

237 * 文件数据写入(如果文件夹和文件不存在,则先创建,再写入)238 *@paramfilePath239 *@paramcontent240 *@paramflag true:如果文件存在且存在内容,则内容换行追加;false:如果文件存在且存在内容,则内容替换241 */

242 public static String fileLinesWrite(String filePath,String content,booleanflag){243 String filedo = "write";244 FileWriter fw = null;245 try{246 File file=newFile(filePath);247 //如果文件夹不存在,则创建文件夹

248 if (!file.getParentFile().exists()){249 file.getParentFile().mkdirs();250 }251 if(!file.exists()){//如果文件不存在,则创建文件,写入第一行内容

252 file.createNewFile();253 fw = newFileWriter(file);254 filedo = "create";255 }else{//如果文件存在,则追加或替换内容

256 fw = newFileWriter(file, flag);257 }258 } catch(IOException e) {259 e.printStackTrace();260 }261 PrintWriter pw = newPrintWriter(fw);262 pw.println(content);263 pw.flush();264 try{265 fw.flush();266 pw.close();267 fw.close();268 } catch(IOException e) {269 e.printStackTrace();270 }271 returnfiledo;272 }273

274 /**

275 * 写文件276 *@paramins277 *@paramout278 */

279 public static voidwriteIntoOut(InputStream ins, OutputStream out) {280 byte[] bb = new byte[10 * 1024];281 try{282 int cnt =ins.read(bb);283 while (cnt > 0) {284 out.write(bb, 0, cnt);285 cnt =ins.read(bb);286 }287 } catch(IOException e) {288 e.printStackTrace();289 } finally{290 try{291 out.flush();292 ins.close();293 out.close();294 } catch(IOException e) {295 e.printStackTrace();296 }297 }298 }299

300 /**

301 * 判断list中元素是否完全相同(完全相同返回true,否则返回false)302 *@paramlist303 *@return

304 */

305 private static boolean hasSame(List extends Object>list){306 if(null ==list)307 return false;308 return 1 == new HashSet(list).size();309 }310

311 /**

312 * 判断list中是否有重复元素(无重复返回true,否则返回false)313 *@paramlist314 *@return

315 */

316 private static boolean hasSame2(List extends Object>list){317 if(null ==list)318 return false;319 return list.size() == new HashSet(list).size();320 }321

322 /**

323 * 增加/减少天数324 *@paramdate325 *@paramnum326 *@return

327 */

328 public static Date DateAddOrSub(Date date, intnum) {329 Calendar startDT =Calendar.getInstance();330 startDT.setTime(date);331 startDT.add(Calendar.DAY_OF_MONTH, num);332 returnstartDT.getTime();333 }334 //https://www.cnblogs.com/chenhuan001/p/6575053.html

335 /**

336 * 递归删除文件或者目录337 *@paramfile_path338 */

339 public static voiddeleteEveryThing(String file_path) {340 try{341 File file=newFile(file_path);342 if(!file.exists()){343 return;344 }345 if(file.isFile()){346 file.delete();347 }else{348 File[] files =file.listFiles();349 for(int i=0;i

351 deleteEveryThing(root);352 }353 file.delete();354 }355 } catch(Exception e) {356 System.out.println("删除文件失败");357 }358 }359 /**

360 * 创建目录361 *@paramdir_path362 */

363 public static voidmkDir(String dir_path) {364 File myFolderPath = newFile(dir_path);365 try{366 if (!myFolderPath.exists()) {367 myFolderPath.mkdir();368 }369 } catch(Exception e) {370 System.out.println("新建目录操作出错");371 e.printStackTrace();372 }373 }374

375 //https://blog.csdn.net/lovoo/article/details/77899627

376 /**

377 * 判断指定的文件是否存在。378 *379 *@paramfileName380 *@return

381 */

382 public static booleanisFileExist(String fileName) {383 return newFile(fileName).isFile();384 }385

386 /*得到文件后缀名387 *388 * @param fileName389 * @return390 */

391 public staticString getFileExt(String fileName) {392 int point = fileName.lastIndexOf('.');393 int length =fileName.length();394 if (point == -1 || point == length - 1) {395 return "";396 } else{397 return fileName.substring(point + 1, length);398 }399 }400

401 /**

402 * 删除文件夹及其下面的子文件夹403 *404 *@paramdir405 *@throwsIOException406 */

407 public static void deleteDir(File dir) throwsIOException {408 if(dir.isFile())409 throw new IOException("IOException -> BadInputException: not a directory.");410 File[] files =dir.listFiles();411 if (files != null) {412 for (int i = 0; i < files.length; i++) {413 File file =files[i];414 if(file.isFile()) {415 file.delete();416 } else{417 deleteDir(file);418 }419 }420 }421 dir.delete();422 }423

424 /**

425 * 复制文件426 *427 *@paramsrc428 *@paramdst429 *@throwsException430 */

431 public static void copy(File src, File dst) throwsException {432 int BUFFER_SIZE = 4096;433 InputStream in = null;434 OutputStream out = null;435 try{436 in = new BufferedInputStream(newFileInputStream(src), BUFFER_SIZE);437 out = new BufferedOutputStream(newFileOutputStream(dst), BUFFER_SIZE);438 byte[] buffer = new byte[BUFFER_SIZE];439 int len = 0;440 while ((len = in.read(buffer)) > 0) {441 out.write(buffer, 0, len);442 }443 } catch(Exception e) {444 throwe;445 } finally{446 if (null !=in) {447 try{448 in.close();449 } catch(IOException e) {450 e.printStackTrace();451 }452 in = null;453 }454 if (null !=out) {455 try{456 out.close();457 } catch(IOException e) {458 e.printStackTrace();459 }460 out = null;461 }462 }463 }464

465

466 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值