文件操做經常使用功能:html
1 package com.suning.yypt.business.report; 2 3 import java.io.*; 4 import java.util.*; 5 6 @SuppressWarnings({"resource","unused"}) 7 public class FileUtils { 8 9 /** 10 * 獲取windows/linux的項目根目錄 11 * @return 12 */ 13 public static String 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 return fileUrl; 21 } 22 23 /** 24 * 字符串轉數組 25 * @param str 字符串 26 * @param splitStr 分隔符 27 * @return 28 */ 29 public static String[] 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 return arrayStr; 40 } 41 42 /** 43 * 讀取文件 44 * 45 * @param Path 46 * @return 47 */ 48 public static String ReadFile(String Path) { 49 BufferedReader reader = null; 50 String laststr = ""; 51 try { 52 FileInputStream fileInputStream = new FileInputStream(Path); 53 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); 54 reader = new BufferedReader(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 return laststr; 72 } 73 74 /** 75 * 獲取文件夾下全部文件的名稱 + 模糊查詢(當不須要模糊查詢時,queryStr傳空或null便可) 76 * 1.當路徑不存在時,map返回retType值爲1 77 * 2.當路徑爲文件路徑時,map返回retType值爲2,文件名fileName值爲文件名 78 * 3.當路徑下有文件夾時,map返回retType值爲3,文件名列表fileNameList,文件夾名列表folderNameList 79 * @param folderPath 路徑 80 * @param queryStr 模糊查詢字符串 81 * @return 82 */ 83 public static HashMap<String, Object> getFilesName(String folderPath , String queryStr) { 84 HashMap<String, Object> map = new HashMap<>(); 85 List<String> fileNameList = new ArrayList<>();//文件名列表 86 List<String> folderNameList = new ArrayList<>();//文件夾名列表 87 File f = new File(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 return map; 114 } 115 116 /** 117 * 以行爲單位讀取文件,讀取到最後一行 118 * @param filePath 119 * @return 120 */ 121 public static List<String> readFileContent(String filePath) { 122 BufferedReader reader = null; 123 List<String> listContent = new ArrayList<>(); 124 try { 125 reader = new BufferedReader(new FileReader(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 return listContent; 145 } 146 147 /** 148 * 讀取指定行數據 ,注意:0爲開始行 149 * @param filePath 150 * @param lineNumber 151 * @return 152 */ 153 public static String readLineContent(String filePath,int lineNumber){ 154 BufferedReader reader = null; 155 String lineContent=""; 156 try { 157 reader = new BufferedReader(new FileReader(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 return lineContent; 175 } 176 177 /** 178 * 讀取從beginLine到endLine數據(包含beginLine和endLine),注意:0爲開始行 179 * @param filePath 180 * @param beginLineNumber 開始行 181 * @param endLineNumber 結束行 182 * @return 183 */ 184 public static List<String> readLinesContent(String filePath,int beginLineNumber,int endLineNumber){ 185 List<String> listContent = new ArrayList<>(); 186 try{ 187 int count = 0; 188 BufferedReader reader = new BufferedReader(new FileReader(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 return listContent; 200 } 201 202 /** 203 * 讀取若干文件中全部數據 204 * @param listFilePath 205 * @return 206 */ 207 public static List<String> readFileContent_list(List<String> listFilePath) { 208 List<String> listContent = new ArrayList<>(); 209 for(String filePath : listFilePath){ 210 File file = new File(filePath); 211 BufferedReader reader = null; 212 try { 213 reader = new BufferedReader(new FileReader(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 return listContent; 234 } 235 236 /** 237 * 文件數據寫入(若是文件夾和文件不存在,則先建立,再寫入) 238 * @param filePath 239 * @param content 240 * @param flag true:若是文件存在且存在內容,則內容換行追加;false:若是文件存在且存在內容,則內容替換 241 */ 242 public static String fileLinesWrite(String filePath,String content,boolean flag){ 243 String filedo = "write"; 244 FileWriter fw = null; 245 try { 246 File file=new File(filePath); 247 //若是文件夾不存在,則建立文件夾 248 if (!file.getParentFile().exists()){ 249 file.getParentFile().mkdirs(); 250 } 251 if(!file.exists()){//若是文件不存在,則建立文件,寫入第一行內容 252 file.createNewFile(); 253 fw = new FileWriter(file); 254 filedo = "create"; 255 }else{//若是文件存在,則追加或替換內容 256 fw = new FileWriter(file, flag); 257 } 258 } catch (IOException e) { 259 e.printStackTrace(); 260 } 261 PrintWriter pw = new PrintWriter(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 return filedo; 272 } 273 274 /** 275 * 寫文件 276 * @param ins 277 * @param out 278 */ 279 public static void writeIntoOut(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 * @param list 303 * @return 304 */ 305 private static boolean hasSame(List<? extends Object> list){ 306 if(null == list) 307 return false; 308 return 1 == new HashSet<Object>(list).size(); 309 } 310 311 /** 312 * 判斷list中是否有重複元素(無重複返回true,不然返回false) 313 * @param list 314 * @return 315 */ 316 private static boolean hasSame2(List<? extends Object> list){ 317 if(null == list) 318 return false; 319 return list.size() == new HashSet<Object>(list).size(); 320 } 321 322 /** 323 * 增長/減小天數 324 * @param date 325 * @param num 326 * @return 327 */ 328 public static Date DateAddOrSub(Date date, int num) { 329 Calendar startDT = Calendar.getInstance(); 330 startDT.setTime(date); 331 startDT.add(Calendar.DAY_OF_MONTH, num); 332 return startDT.getTime(); 333 } 334 //https://www.cnblogs.com/chenhuan001/p/6575053.html 335 /** 336 * 遞歸刪除文件或者目錄 337 * @param file_path 338 */ 339 public static void deleteEveryThing(String file_path) { 340 try{ 341 File file=new File(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<files.length;i++){ 350 String root=files[i].getAbsolutePath();//獲得子文件或文件夾的絕對路徑 351 deleteEveryThing(root); 352 } 353 file.delete(); 354 } 355 } catch(Exception e) { 356 System.out.println("刪除文件失敗"); 357 } 358 } 359 /** 360 * 建立目錄 361 * @param dir_path 362 */ 363 public static void mkDir(String dir_path) { 364 File myFolderPath = new File(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 * @param fileName 380 * @return 381 */ 382 public static boolean isFileExist(String fileName) { 383 return new File(fileName).isFile(); 384 } 385 386 /* 獲得文件後綴名 387 * 388 * @param fileName 389 * @return 390 */ 391 public static String 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 * @param dir 405 * @throws IOException 406 */ 407 public static void deleteDir(File dir) throws IOException { 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 * @param src 428 * @param dst 429 * @throws Exception 430 */ 431 public static void copy(File src, File dst) throws Exception { 432 int BUFFER_SIZE = 4096; 433 InputStream in = null; 434 OutputStream out = null; 435 try { 436 in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); 437 out = new BufferedOutputStream(new FileOutputStream(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 throw e; 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 }