文件操作FileUtil.java

  1. packagecom.work.util;
  2. importjava.io.BufferedInputStream;
  3. importjava.io.BufferedOutputStream;
  4. importjava.io.BufferedReader;
  5. importjava.io.BufferedWriter;
  6. importjava.io.File;
  7. importjava.io.FileInputStream;
  8. importjava.io.FileNotFoundException;
  9. importjava.io.FileOutputStream;
  10. importjava.io.IOException;
  11. importjava.io.InputStreamReader;
  12. importjava.io.OutputStreamWriter;
  13. importjava.io.RandomAccessFile;
  14. importjava.io.StringReader;
  15. importjava.util.ArrayList;
  16. importjava.util.List;
  17. importjava.util.zip.ZipEntry;
  18. importjava.util.zip.ZipOutputStream;
  19. importorg.apache.commons.logging.Log;
  20. importorg.apache.commons.logging.LogFactory;
  21. /**
  22. *日期:2008-2-1412:05:18<br/>
  23. *project:zxj<br/>
  24. *作者:wangmingjie<br/>
  25. */
  26. publicclassFileUtil{
  27. privatestaticLoglog=LogFactory.getLog(FileUtil.class);
  28. /**
  29. *創建單個文件夾。
  30. *
  31. *@paramdir
  32. *@paramignoreIfExitst
  33. *true表示如果文件夾存在就不再創建了。false是重新創建。
  34. *@throwsIOException
  35. */
  36. publicstaticvoidcreateDir(Stringdir,booleanignoreIfExitst)
  37. throwsIOException{
  38. Filefile=newFile(dir);
  39. if(ignoreIfExitst&&file.exists()){
  40. return;
  41. }
  42. if(file.mkdir()==false){
  43. thrownewIOException("Cannotcreatethedirectory="+dir);
  44. }
  45. }
  46. /**
  47. *創建多個文件夾
  48. *
  49. *@paramdir
  50. *@paramignoreIfExitst
  51. *@throwsIOException
  52. */
  53. publicstaticvoidcreateDirs(Stringdir,booleanignoreIfExitst)
  54. throwsIOException{
  55. Filefile=newFile(dir);
  56. if(ignoreIfExitst&&file.exists()){
  57. return;
  58. }
  59. if(file.mkdirs()==false){
  60. thrownewIOException("Cannotcreatedirectories="+dir);
  61. }
  62. }
  63. /**
  64. *刪除一個文件。
  65. *
  66. *@paramfilename
  67. *@throwsIOException
  68. */
  69. publicstaticvoiddeleteFile(Stringfilename)throwsIOException{
  70. Filefile=newFile(filename);
  71. log.trace("Deletefile="+filename);
  72. if(file.isDirectory()){
  73. thrownewIOException(
  74. "IOException->BadInputException:notafile.");
  75. }
  76. if(file.exists()==false){
  77. thrownewIOException(
  78. "IOException->BadInputException:fileisnotexist.");
  79. }
  80. if(file.delete()==false){
  81. thrownewIOException("Cannotdeletefile.filename="+filename);
  82. }
  83. }
  84. /**
  85. *刪除文件夾及其下面的子文件夾
  86. *
  87. *@paramdir
  88. *@throwsIOException
  89. */
  90. publicstaticvoiddeleteDir(Filedir)throwsIOException{
  91. if(dir.isFile())
  92. thrownewIOException(
  93. "IOException->BadInputException:notadirectory.");
  94. File[]files=dir.listFiles();
  95. if(files!=null){
  96. for(inti=0;i<files.length;i++){
  97. Filefile=files[i];
  98. if(file.isFile()){
  99. file.delete();
  100. }else{
  101. deleteDir(file);
  102. }
  103. }
  104. }//if
  105. dir.delete();
  106. }
  107. publicstaticStringgetPathSeparator(){
  108. returnjava.io.File.pathSeparator;
  109. }
  110. publicstaticStringgetFileSeparator(){
  111. returnjava.io.File.separator;
  112. }
  113. /**
  114. *列出指定文件目錄下面的文件信息。
  115. *
  116. *@paramdir
  117. *@return
  118. *@throwsIOException
  119. */
  120. publicstaticList<FileInfo>getFiles(Filedir)throwsIOException{
  121. if(dir.isFile())
  122. thrownewIOException("BadInputException:notadirectory.");
  123. if(!dir.exists()){
  124. thrownewIOException("don'texist");
  125. }
  126. File[]files=dir.listFiles();
  127. intLEN=0;
  128. if(files!=null){
  129. LEN=files.length;
  130. }
  131. List<FileInfo>l=newArrayList<FileInfo>();
  132. longtempFLen=0;//文件長度
  133. for(inti=0;i<LEN;i++){
  134. FileInfotemp=newFileInfo();
  135. temp.setFileName(files[i].getName());
  136. temp.setIsDir(files[i].isDirectory());
  137. //是文件,且包含.
  138. if(files[i].isFile()){
  139. if(files[i].getName().lastIndexOf(".")!=-1)
  140. temp.setFileType(files[i].getName().substring(
  141. files[i].getName().lastIndexOf(".")));
  142. }else{
  143. temp.setFileType("文件夾");
  144. }
  145. tempFLen=files[i].length();
  146. temp.setFileLen(tempFLen);
  147. if(tempFLen/1024/1024/1024>0){
  148. temp.setFileLength(files[i].length()/1024/1024/1024+"G");
  149. }elseif(tempFLen/1024/1024>0){
  150. temp.setFileLength(files[i].length()/1024/1024+"M");
  151. }elseif(tempFLen/1024>0){
  152. temp.setFileLength(files[i].length()/1024+"K");
  153. }else{
  154. temp.setFileLength(tempFLen+"byte");
  155. }
  156. temp.setFilePath(files[i].getAbsolutePath().replaceAll("[\\\\]","/"));
  157. temp.setLastModifiedTime(com.work.util.DateUtil
  158. .getDateTime(files[i].lastModified()));
  159. temp.setIsHidden(files[i].isHidden());
  160. temp.setAuthor(null);
  161. temp.setVersion(null);
  162. temp.setFileClass(null);
  163. temp.setRemark(null);
  164. l.add(temp);
  165. }
  166. returnl;
  167. }
  168. /**
  169. *獲取到目錄下面文件的大小。包含了子目錄。
  170. *
  171. *@paramdir
  172. *@return
  173. *@throwsIOException
  174. */
  175. publicstaticlonggetDirLength(Filedir)throwsIOException{
  176. if(dir.isFile())
  177. thrownewIOException("BadInputException:notadirectory.");
  178. longsize=0;
  179. File[]files=dir.listFiles();
  180. if(files!=null){
  181. for(inti=0;i<files.length;i++){
  182. Filefile=files[i];
  183. //file.getName();
  184. //System.out.println(file.getName());
  185. longlength=0;
  186. if(file.isFile()){
  187. length=file.length();
  188. }else{
  189. length=getDirLength(file);
  190. }
  191. size+=length;
  192. }//for
  193. }//if
  194. returnsize;
  195. }
  196. /**
  197. *將文件清空。
  198. *
  199. *@paramsrcFilename
  200. *@throwsIOException
  201. */
  202. publicstaticvoidemptyFile(StringsrcFilename)throwsIOException{
  203. FilesrcFile=newFile(srcFilename);
  204. if(!srcFile.exists()){
  205. thrownewFileNotFoundException("Cannotfindthefile:"
  206. +srcFile.getAbsolutePath());
  207. }
  208. if(!srcFile.canWrite()){
  209. thrownewIOException("Cannotwritethefile:"
  210. +srcFile.getAbsolutePath());
  211. }
  212. FileOutputStreamoutputStream=newFileOutputStream(srcFilename);
  213. outputStream.close();
  214. }
  215. /**
  216. *WritecontenttoafileNamewiththedestEncoding寫文件。如果此文件不存在就創建一個。
  217. *
  218. *@paramcontent
  219. *String
  220. *@paramfileName
  221. *String
  222. *@paramdestEncoding
  223. *String
  224. *@throwsFileNotFoundException
  225. *@throwsIOException
  226. */
  227. publicstaticvoidwriteFile(Stringcontent,StringfileName,
  228. StringdestEncoding)throwsFileNotFoundException,IOException{
  229. Filefile=null;
  230. try{
  231. file=newFile(fileName);
  232. if(!file.exists()){
  233. if(file.createNewFile()==false){
  234. thrownewIOException("createfile'"+fileName
  235. +"'failure.");
  236. }
  237. }
  238. if(file.isFile()==false){
  239. thrownewIOException("'"+fileName+"'isnotafile.");
  240. }
  241. if(file.canWrite()==false){
  242. thrownewIOException("'"+fileName+"'isaread-onlyfile.");
  243. }
  244. }finally{
  245. //wedonthavetocloseFilehere
  246. }
  247. BufferedWriterout=null;
  248. try{
  249. FileOutputStreamfos=newFileOutputStream(fileName);
  250. out=newBufferedWriter(newOutputStreamWriter(fos,destEncoding));
  251. out.write(content);
  252. out.flush();
  253. }catch(FileNotFoundExceptionfe){
  254. log.error("Error",fe);
  255. throwfe;
  256. }catch(IOExceptione){
  257. log.error("Error",e);
  258. throwe;
  259. }finally{
  260. try{
  261. if(out!=null)
  262. out.close();
  263. }catch(IOExceptionex){
  264. }
  265. }
  266. }
  267. /**
  268. *讀取文件的內容,並將文件內容以字符串的形式返回。
  269. *
  270. *@paramfileName
  271. *@paramsrcEncoding
  272. *@return
  273. *@throwsFileNotFoundException
  274. *@throwsIOException
  275. */
  276. publicstaticStringreadFile(StringfileName,StringsrcEncoding)
  277. throwsFileNotFoundException,IOException{
  278. Filefile=null;
  279. try{
  280. file=newFile(fileName);
  281. if(file.isFile()==false){
  282. thrownewIOException("'"+fileName+"'isnotafile.");
  283. }
  284. }finally{
  285. //wedonthavetocloseFilehere
  286. }
  287. BufferedReaderreader=null;
  288. try{
  289. StringBufferresult=newStringBuffer(1024);
  290. FileInputStreamfis=newFileInputStream(fileName);
  291. reader=newBufferedReader(newInputStreamReader(fis,srcEncoding));
  292. char[]block=newchar[512];
  293. while(true){
  294. intreadLength=reader.read(block);
  295. if(readLength==-1)
  296. break;//endoffile
  297. result.append(block,0,readLength);
  298. }
  299. returnresult.toString();
  300. }catch(FileNotFoundExceptionfe){
  301. log.error("Error",fe);
  302. throwfe;
  303. }catch(IOExceptione){
  304. log.error("Error",e);
  305. throwe;
  306. }finally{
  307. try{
  308. if(reader!=null)
  309. reader.close();
  310. }catch(IOExceptionex){
  311. }
  312. }
  313. }
  314. /*
  315. *1ABC2abCGiasudoctudong1laycathay5dong=>1-->53ABC
  316. */
  317. publicstaticString[]getLastLines(Filefile,intlinesToReturn)
  318. throwsIOException,FileNotFoundException{
  319. finalintAVERAGE_CHARS_PER_LINE=250;
  320. finalintBYTES_PER_CHAR=2;
  321. RandomAccessFilerandomAccessFile=null;
  322. StringBufferbuffer=newStringBuffer(linesToReturn
  323. *AVERAGE_CHARS_PER_LINE);
  324. intlineTotal=0;
  325. try{
  326. randomAccessFile=newRandomAccessFile(file,"r");
  327. longbyteTotal=randomAccessFile.length();
  328. longbyteEstimateToRead=linesToReturn*AVERAGE_CHARS_PER_LINE
  329. *BYTES_PER_CHAR;
  330. longoffset=byteTotal-byteEstimateToRead;
  331. if(offset<0){
  332. offset=0;
  333. }
  334. randomAccessFile.seek(offset);
  335. //log.debug("SKIPIS::"+offset);
  336. Stringline=null;
  337. StringlineUTF8=null;
  338. while((line=randomAccessFile.readLine())!=null){
  339. lineUTF8=newString(line.getBytes("ISO8859_1"),"UTF-8");
  340. lineTotal++;
  341. buffer.append(lineUTF8).append("\n");
  342. }
  343. }finally{
  344. if(randomAccessFile!=null){
  345. try{
  346. randomAccessFile.close();
  347. }catch(IOExceptionex){
  348. }
  349. }
  350. }
  351. String[]resultLines=newString[linesToReturn];
  352. BufferedReaderin=null;
  353. try{
  354. in=newBufferedReader(newStringReader(buffer.toString()));
  355. intstart=lineTotal/*+2*/-linesToReturn;//Ex:55-10=45
  356. //~offset
  357. if(start<0)
  358. start=0;//notstartline
  359. for(inti=0;i<start;i++){
  360. in.readLine();//loopuntiltheoffset.Ex:loop0,1~~2
  361. //lines
  362. }
  363. inti=0;
  364. Stringline=null;
  365. while((line=in.readLine())!=null){
  366. resultLines[i]=line;
  367. i++;
  368. }
  369. }catch(IOExceptionie){
  370. log.error("Error"+ie);
  371. throwie;
  372. }finally{
  373. if(in!=null){
  374. try{
  375. in.close();
  376. }catch(IOExceptionex){
  377. }
  378. }
  379. }
  380. returnresultLines;
  381. }
  382. /**
  383. *單個文件拷貝。
  384. *
  385. *@paramsrcFilename
  386. *@paramdestFilename
  387. *@paramoverwrite
  388. *@throwsIOException
  389. */
  390. publicstaticvoidcopyFile(StringsrcFilename,StringdestFilename,
  391. booleanoverwrite)throwsIOException{
  392. FilesrcFile=newFile(srcFilename);
  393. //首先判斷源文件是否存在
  394. if(!srcFile.exists()){
  395. thrownewFileNotFoundException("Cannotfindthesourcefile:"
  396. +srcFile.getAbsolutePath());
  397. }
  398. //判斷源文件是否可讀
  399. if(!srcFile.canRead()){
  400. thrownewIOException("Cannotreadthesourcefile:"
  401. +srcFile.getAbsolutePath());
  402. }
  403. FiledestFile=newFile(destFilename);
  404. if(overwrite==false){
  405. //目標文件存在就不覆蓋
  406. if(destFile.exists())
  407. return;
  408. }else{
  409. //如果要覆蓋已經存在的目標文件,首先判斷是否目標文件可寫。
  410. if(destFile.exists()){
  411. if(!destFile.canWrite()){
  412. thrownewIOException("Cannotwritethedestinationfile:"
  413. +destFile.getAbsolutePath());
  414. }
  415. }else{
  416. //不存在就創建一個新的空文件。
  417. if(!destFile.createNewFile()){
  418. thrownewIOException("Cannotwritethedestinationfile:"
  419. +destFile.getAbsolutePath());
  420. }
  421. }
  422. }
  423. BufferedInputStreaminputStream=null;
  424. BufferedOutputStreamoutputStream=null;
  425. byte[]block=newbyte[1024];
  426. try{
  427. inputStream=newBufferedInputStream(newFileInputStream(srcFile));
  428. outputStream=newBufferedOutputStream(newFileOutputStream(
  429. destFile));
  430. while(true){
  431. intreadLength=inputStream.read(block);
  432. if(readLength==-1)
  433. break;//endoffile
  434. outputStream.write(block,0,readLength);
  435. }
  436. }finally{
  437. if(inputStream!=null){
  438. try{
  439. inputStream.close();
  440. }catch(IOExceptionex){
  441. //justignore
  442. }
  443. }
  444. if(outputStream!=null){
  445. try{
  446. outputStream.close();
  447. }catch(IOExceptionex){
  448. //justignore
  449. }
  450. }
  451. }
  452. }
  453. /**
  454. *單個文件拷貝。
  455. *
  456. *@paramsrcFile
  457. *@paramdestFile
  458. *@paramoverwrite
  459. *是否覆蓋目的文件
  460. *@throwsIOException
  461. */
  462. publicstaticvoidcopyFile(FilesrcFile,FiledestFile,booleanoverwrite)
  463. throwsIOException{
  464. //首先判斷源文件是否存在
  465. if(!srcFile.exists()){
  466. thrownewFileNotFoundException("Cannotfindthesourcefile:"
  467. +srcFile.getAbsolutePath());
  468. }
  469. //判斷源文件是否可讀
  470. if(!srcFile.canRead()){
  471. thrownewIOException("Cannotreadthesourcefile:"
  472. +srcFile.getAbsolutePath());
  473. }
  474. if(overwrite==false){
  475. //目標文件存在就不覆蓋
  476. if(destFile.exists())
  477. return;
  478. }else{
  479. //如果要覆蓋已經存在的目標文件,首先判斷是否目標文件可寫。
  480. if(destFile.exists()){
  481. if(!destFile.canWrite()){
  482. thrownewIOException("Cannotwritethedestinationfile:"
  483. +destFile.getAbsolutePath());
  484. }
  485. }else{
  486. //不存在就創建一個新的空文件。
  487. if(!destFile.createNewFile()){
  488. thrownewIOException("Cannotwritethedestinationfile:"
  489. +destFile.getAbsolutePath());
  490. }
  491. }
  492. }
  493. BufferedInputStreaminputStream=null;
  494. BufferedOutputStreamoutputStream=null;
  495. byte[]block=newbyte[1024];
  496. try{
  497. inputStream=newBufferedInputStream(newFileInputStream(srcFile));
  498. outputStream=newBufferedOutputStream(newFileOutputStream(
  499. destFile));
  500. while(true){
  501. intreadLength=inputStream.read(block);
  502. if(readLength==-1)
  503. break;//endoffile
  504. outputStream.write(block,0,readLength);
  505. }
  506. }finally{
  507. if(inputStream!=null){
  508. try{
  509. inputStream.close();
  510. }catch(IOExceptionex){
  511. //justignore
  512. }
  513. }
  514. if(outputStream!=null){
  515. try{
  516. outputStream.close();
  517. }catch(IOExceptionex){
  518. //justignore
  519. }
  520. }
  521. }
  522. }
  523. /**
  524. *拷貝文件,從源文件夾拷貝文件到目的文件夾。<br>
  525. *參數源文件夾和目的文件夾,最後都不要帶文件路徑符號,例如:c:/aa正確,c:/aa/錯誤。
  526. *
  527. *@paramsrcDirName
  528. *源文件夾名稱,例如:c:/test/aa或者c:\\test\\aa
  529. *@paramdestDirName
  530. *目的文件夾名稱,例如:c:/test/aa或者c:\\test\\aa
  531. *@paramoverwrite
  532. *是否覆蓋目的文件夾下面的文件。
  533. *@throwsIOException
  534. */
  535. publicstaticvoidcopyFiles(StringsrcDirName,StringdestDirName,
  536. booleanoverwrite)throwsIOException{
  537. FilesrcDir=newFile(srcDirName);//聲明源文件夾
  538. //首先判斷源文件夾是否存在
  539. if(!srcDir.exists()){
  540. thrownewFileNotFoundException(
  541. "Cannotfindthesourcedirectory:"
  542. +srcDir.getAbsolutePath());
  543. }
  544. FiledestDir=newFile(destDirName);
  545. if(overwrite==false){
  546. if(destDir.exists()){
  547. //donothing
  548. }else{
  549. if(destDir.mkdirs()==false){
  550. thrownewIOException(
  551. "Cannotcreatethedestinationdirectories="
  552. +destDir);
  553. }
  554. }
  555. }else{
  556. //覆蓋存在的目的文件夾
  557. if(destDir.exists()){
  558. //donothing
  559. }else{
  560. //createanewdirectory
  561. if(destDir.mkdirs()==false){
  562. thrownewIOException(
  563. "Cannotcreatethedestinationdirectories="
  564. +destDir);
  565. }
  566. }
  567. }
  568. //循環查找源文件夾目錄下面的文件(屏蔽子文件夾),然後將其拷貝到指定的目的文件夾下面。
  569. File[]srcFiles=srcDir.listFiles();
  570. if(srcFiles==null||srcFiles.length<1){
  571. //thrownewIOException("Cannotfindanyfilefromsource
  572. //directory!!!");
  573. return;//donothing
  574. }
  575. //開始複製文件
  576. intSRCLEN=srcFiles.length;
  577. for(inti=0;i<SRCLEN;i++){
  578. //FiletempSrcFile=srcFiles[i];
  579. FiledestFile=newFile(destDirName+File.separator
  580. +srcFiles[i].getName());
  581. //注意構造文件對象時候,文件名字符串中不能包含文件路徑分隔符";".
  582. //log.debug(destFile);
  583. if(srcFiles[i].isFile()){
  584. copyFile(srcFiles[i],destFile,overwrite);
  585. }else{
  586. //在這裏進行遞歸調用,就可以實現子文件夾的拷貝
  587. copyFiles(srcFiles[i].getAbsolutePath(),destDirName
  588. +File.separator+srcFiles[i].getName(),overwrite);
  589. }
  590. }
  591. }
  592. /**
  593. *壓縮文件。注意:中文文件名稱和中文的評論會亂碼。
  594. *@paramsrcFilename
  595. *@paramdestFilename
  596. *@paramoverwrite
  597. *@throwsIOException
  598. */
  599. publicstaticvoidzipFile(StringsrcFilename,StringdestFilename,
  600. booleanoverwrite)throwsIOException{
  601. FilesrcFile=newFile(srcFilename);
  602. //首先判斷源文件是否存在
  603. if(!srcFile.exists()){
  604. thrownewFileNotFoundException("Cannotfindthesourcefile:"
  605. +srcFile.getAbsolutePath());
  606. }
  607. //判斷源文件是否可讀
  608. if(!srcFile.canRead()){
  609. thrownewIOException("Cannotreadthesourcefile:"
  610. +srcFile.getAbsolutePath());
  611. }
  612. if(destFilename==null||destFilename.trim().equals("")){
  613. destFilename=srcFilename+".zip";
  614. }else{
  615. destFilename+=".zip";
  616. }
  617. FiledestFile=newFile(destFilename);
  618. if(overwrite==false){
  619. //目標文件存在就不覆蓋
  620. if(destFile.exists())
  621. return;
  622. }else{
  623. //如果要覆蓋已經存在的目標文件,首先判斷是否目標文件可寫。
  624. if(destFile.exists()){
  625. if(!destFile.canWrite()){
  626. thrownewIOException("Cannotwritethedestinationfile:"
  627. +destFile.getAbsolutePath());
  628. }
  629. }else{
  630. //不存在就創建一個新的空文件。
  631. if(!destFile.createNewFile()){
  632. thrownewIOException("Cannotwritethedestinationfile:"
  633. +destFile.getAbsolutePath());
  634. }
  635. }
  636. }
  637. BufferedInputStreaminputStream=null;
  638. BufferedOutputStreamoutputStream=null;
  639. ZipOutputStreamzipOutputStream=null;
  640. byte[]block=newbyte[1024];
  641. try{
  642. inputStream=newBufferedInputStream(newFileInputStream(srcFile));
  643. outputStream=newBufferedOutputStream(newFileOutputStream(destFile));
  644. zipOutputStream=newZipOutputStream(outputStream);
  645. zipOutputStream.setComment("通過java程序壓縮的");
  646. ZipEntryzipEntry=newZipEntry(srcFile.getName());
  647. zipEntry.setComment("zipEntry通過java程序壓縮的");
  648. zipOutputStream.putNextEntry(zipEntry);
  649. while(true){
  650. intreadLength=inputStream.read(block);
  651. if(readLength==-1)
  652. break;//endoffile
  653. zipOutputStream.write(block,0,readLength);
  654. }
  655. zipOutputStream.flush();
  656. zipOutputStream.finish();
  657. }finally{
  658. if(inputStream!=null){
  659. try{
  660. inputStream.close();
  661. }catch(IOExceptionex){
  662. //justignore
  663. }
  664. }
  665. if(outputStream!=null){
發佈了3 篇原創文章 · 獲贊 0 · 訪問量 2677
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章