文件压缩与删除(整理) (转)

文件压缩与删除(整理) (转)
java 代码
  1. /**
  2. *
  3. * @param inputFileName
  4. * 需要压缩的文件路径
  5. * @param outputFileName
  6. * 输出的文件名
  7. * @throws Exception
  8. */
  9. public boolean zip(String inputFileName, String outputFileName){
  10. boolean bNodFoundFile=true;
  11. ZipOutputStream out = null;
  12. try {
  13. out = new ZipOutputStream(new FileOutputStream(
  14. outputFileName));
  15. zip(out, new File(inputFileName), "");
  16. /*注意当压缩文件夹为空时,将抛出异常*/
  17. out.close();
  18. } catch (IOException e) {
  19. bNodFoundFile=false;
  20. }finally{
  21. if(out!=null){
  22. try {
  23. out.close();
  24. out=null;
  25. } catch (IOException e) {
  26. }
  27. }
  28. }
  29. return bNodFoundFile;
  30. }
  31. private void zip(ZipOutputStream out, File f, String base){
  32. FileInputStream in =null;
  33. try{
  34. if (f.isDirectory()) {
  35. File[] fl = f.listFiles();
  36. /*此处解决压缩未端数据不正确*/
  37. if (System.getProperty("os.name").startsWith("Windows")) {
  38. base = base.length() == 0 ? "" : base + "\";
  39. out.putNextEntry(new ZipEntry(base));
  40. } else {
  41. base = base.length() == 0 ? "" : base + "/";
  42. out.putNextEntry(new ZipEntry(base));
  43. }
  44. int indexSize=fl.length;
  45. for (int i = 0; i < indexSize; i++) {
  46. zip(out, fl[i], base + fl[i].getName());
  47. }
  48. } else {
  49. out.putNextEntry(new ZipEntry(base));
  50. in = new FileInputStream(f);
  51. int b;
  52. byte[] buffer = new byte[4096];
  53. while ((b = in.read(buffer)) != -1) {
  54. out.write(buffer,0,b);
  55. }
  56. }
  57. }catch(IOException e){
  58. } finally{
  59. try {
  60. if(in!=null){
  61. in.close();
  62. in=null;
  63. }
  64. } catch (IOException e1) {
  65. }
  66. }
  67. }
  68. /**
  69. * 删文件
  70. * @param deleteFilePath
  71. * 删除文件路径
  72. */
  73. public void deleteFile(final String deleteFilePath){
  74. File file=new File(deleteFilePath);
  75. deleteFile(file);
  76. file.delete();
  77. }
  78. /**
  79. * 实施删除文件
  80. * @param file
  81. */
  82. private void deleteFile(File file){
  83. if(file.isDirectory()){
  84. File[] fl = file.listFiles();
  85. int indexSize=fl.length;
  86. for(int i=0; i
  87. deleteFile(fl[i]);
  88. }
  89. /*此处删除目录*/
  90. file.delete();
  91. }else{
  92. /*此处删除文件*/
  93. file.delete();
  94. }
  95. }

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12467/viewspace-148291/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/12467/viewspace-148291/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值