http://blog.csdn.net/isea533/article/details/7995472

Java解压缩zip - 多个文件(包括文件夹)

在项目存放图片的文件夹写入

/.nomedia

  1. File nomedia = new File(filePath + "/.nomedia" );  
  2.                if (! nomedia.exists())  
  3.                       try {  
  4.                             nomedia.createNewFile();  
  5.                      } catch (Exception e) {  
  6.                            e.printStackTrace();  
  7.                      }  

filePath  为你想隐藏的目录

生成.nomedia 文件夹
原理是SD卡中, 图库会自动跳过有.nomedia文件 ,将扫描到的图片、铃声 等多媒体文件media_type设置为0
备注: 
media_type 的值 0 : 普通文件 , 1 : 图片文件 , 2: 音频文件 , 3: 视频文件)). 
而图库显示的文件是(media_type = 1 or media_type = 3
 
  1. /** 
  2.      * 获取内置SD卡路径 
  3.      * @return 
  4.      */  
  5.     public String getInnerSDCardPath() {    
  6.         return Environment.getExternalStorageDirectory().getPath();    
  7.     }
 

/    public static v
package com.lhj.filetest.filetest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

public class MainActivity extends Activity implements View.OnClickListener {
    //java.io.File f = new File("d:/111/222/333");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button newFile = (Button) findViewById(R.id.create_file);
        newFile.setOnClickListener(this);
        Button delFile = (Button) findViewById(R.id.del_file);
        delFile.setOnClickListener(this);
        Button unzip_file = (Button) findViewById(R.id.unzip_file);
        unzip_file.setOnClickListener(this);
        Button w_file = (Button) findViewById(R.id.write_file);
        w_file.setOnClickListener(this);
    }

    public String getInnerSDCardPath() {
        return Environment.getExternalStorageDirectory().getPath();
    }

    String path = Environment.getExternalStorageDirectory().getPath() + "/esales/report";
    String delPath = Environment.getExternalStorageDirectory().getPath() + "/esales";
    String txtPath = path + "/temp.txt";

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.create_file:
                File file = new File(path);
                if (file.exists()) {
                    Toast.makeText(this, " file is exists", Toast.LENGTH_SHORT).show();
                } else if (createDir(file)) {
                    Toast.makeText(this, "new file success", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "new file fail", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.del_file:
                File file2 = new File(delPath);
                if (deleteDir(file2)) {
                    Toast.makeText(this, "delete file success", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "delete file fail", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.unzip_file:
                //zipDecompressing();
                String zipPath = Environment.getExternalStorageDirectory().getPath() + "/temp.zip";
                String unzipPath=  Environment.getExternalStorageDirectory().getPath() + "/AAA/";
                try {
                    unZipFiles(zipPath, unzipPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.write_file:
                File file4 = new File(txtPath);
                if (writeTxtFile("12331  : 你ddd好", file4)) {
                    Toast.makeText(this, "write file success", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "write file fail", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }


    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     * If a deletion fails, the method stops attempting to
     * delete and returns "false".
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }

    private static boolean createDir(File file) {
        return file.mkdirs();
    }

    //写入文件(覆盖原來的內容)
    public static boolean writeTxtFile(String content, File fileName) {
        boolean flag = false;
        FileOutputStream o;
        try {
            o = new FileOutputStream(fileName);
            o.write(content.getBytes("UTF-8"));
            o.close();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return flag;
    }

    /**
     * 解压到指定目录
     * @param zipPath
     * @param descDir
     * @author isea533
     */
    public static void unZipFiles(String zipPath,String descDir)throws IOException{
        unZipFiles(new File(zipPath), descDir);
    }
    /**
     * 解压文件到指定目录
     * @param zipFile
     * @param descDir
     * @author isea533
     */
    public static void unZipFiles(File zipFile,String descDir)throws IOException{
        File pathFile = new File(descDir);
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }
        ZipFile zip = new ZipFile(zipFile);
        for(Enumeration entries = zip.entries();entries.hasMoreElements();){
            ZipEntry entry = (ZipEntry)entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");;
            //判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if(!file.exists()){
                file.mkdirs();
            }
            //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if(new File(outPath).isDirectory()){
                continue;
            }
            //输出文件路径信息
            System.out.println(outPath);

            OutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while((len=in.read(buf1))>0){
                out.write(buf1,0,len);
            }
            in.close();
            out.close();
        }
        System.out.println("******************解压完毕********************");
    }
}

 

oidunZipFiles(File zipFile,String descDir)throws IOException{        File pathFile = new File(descDir);        if(!pathFile.exists()){            pathFile.mkdirs();        }        ZipFile zip = new ZipFile(zipFile);        for(Enumeration entries = zip.entries();entries.hasMoreElements();){            ZipEntry entry = (ZipEntry)entries.nextElement();            String zipEntryName = entry.getName();            InputStream in = zip.getInputStream(entry);            String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");;            //判断路径是否存在,不存在则创建文件路径            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));            if(!file.exists()){                file.mkdirs();            }            //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压            if(new File(outPath).isDirectory()){                continue;            }            //输出文件路径信息            System.out.println(outPath);            OutputStream out = new FileOutputStream(outPath);            byte[] buf1 = new byte[1024];            int len;            while((len=in.read(buf1))>0){                out.write(buf1,0,len);            }            in.close();            out.close();        }        System.out.println("******************解压完毕********************");    }
 import java.io.File;
import java.io.IOException;

public class Main {

    public static void main(String[] args) {

        File file = new File("d:\\test_file.txt");
        Main.judeFileExists(file);

        File dir = new File("d:\\test_dir");
        Main.judeDirExists(dir);
    }

    // 判断文件是否存在
    public static void judeFileExists(File file) {

        if (file.exists()) {
            System.out.println("file exists");
        } else {
            System.out.println("file not exists, create it ...");
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    // 判断文件夹是否存在
    public static void judeDirExists(File file) {

        if (file.exists()) {
            if (file.isDirectory()) {
                System.out.println("dir exists");
            } else {
                System.out.println("the same name file exists, can not create dir");
            }
        } else {
            System.out.println("dir not exists, create it ...");
            file.mkdir();
        }

    }

}
    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
       //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }
    /**
     *测试
     */
    public static void main(String[] args) {
        String newDir2 = "new_dir2";
        boolean success = deleteDir(new File(newDir2));
        if (success) {
            System.out.println("Successfully deleted populated directory: " + newDir2);
        } else {
            System.out.println("Failed to delete populated directory: " + newDir2);
        }     
    }
}
/** 
  * 读TXT文件内容 
  * @param fileName 
  * @return 
  */  
 public static String readTxtFile(File fileName)throws Exception{  
  String result=null;  
  FileReader fileReader=null;  
  BufferedReader bufferedReader=null;  
  try{  
   fileReader=new FileReader(fileName);  
   bufferedReader=new BufferedReader(fileReader);  
   try{  
    String read=null;  
    while((read=bufferedReader.readLine())!=null){  
     result=result+read+"\r\n";  
    }  
   }catch(Exception e){  
    e.printStackTrace();  
   }  
  }catch(Exception e){  
   e.printStackTrace();  
  }finally{  
   if(bufferedReader!=null){  
    bufferedReader.close();  
   }  
   if(fileReader!=null){  
    fileReader.close();  
   }  
  }  
  System.out.println("读取出来的文件内容是:"+"\r\n"+result);  
  return result;  
 }  
   
 //写入文件  
 public static boolean writeTxtFile(String content,File  fileName)throws Exception{  
  RandomAccessFile mm=null;  
  boolean flag=false;  
  FileOutputStream o=null;  
  try {  
   o = new FileOutputStream(fileName);  
      o.write(content.getBytes("GBK"));  
      o.close();  
//   mm=new RandomAccessFile(fileName,"rw");  
//   mm.writeBytes(content);  
   flag=true;  
  } catch (Exception e) {  
   // TODO: handle exception  
   e.printStackTrace();  
  }finally{  
   if(mm!=null){  
    mm.close();  
   }  
  }  
  return flag;  
 }  
  

import java.io.File;
 
public class Main {
    public static void main(String[] argv) throws Exception {
        File dir = new File("../java");
        String[] children = dir.list();
        if (children == null) {
            System.out.println("该目录不存在");
        }
        else {
            for (int i = 0; i < children.length; i++) {
                String filename = children[i];
                System.out.println(filename);
            }
        }
   以上代码运行输出结果为:

Car.class
FileUtil.class
FileUtil.java
HelloWorld.class
HelloWorld.java
HelloWorldDebug.class
HelloWorldDebug.java

 

 

 


posted @ 2017-03-05 14:38 马骝 阅读(237) 评论(0) 推荐(0)
摘要: 使用第三方库出现找不到so库UnsatisfiedLinkError错误的原因以及解决方案 字数1563 阅读913 评论2 喜欢2 在开发项目的时候我们免不了使用一些第三方的库来进行快速开发,有些第三方库只是简单的一个jar包,但是有些使用了jni开发,因此会包含so库文件,这个时候如果不消息我们就会遇到一个错误:java.lang.UnsatisfiedLinkError; 最近经常遇到... 阅读全文
posted @ 2016-11-30 22:12 马骝 阅读(2051) 评论(0) 推荐(0)
摘要: public static String convertFileSize(long size) { long kb = 1024; long mb = kb * 1024; long gb = mb * 1024; if (size >= gb) { return String.format("%.1f ... 阅读全文
posted @ 2016-10-08 21:53 马骝 阅读(173) 评论(0) 推荐(0)
摘要: 三、Bitmap剪切的封装 实际使用中,因为项目需要时常需要对基本功能进行封装,下面是一段封装的代码,仅供参考。 阅读全文
posted @ 2016-09-12 23:12 马骝 阅读(404) 评论(0) 推荐(0)
摘要: 实现Activity间的共享控件转场动画 字数1210 阅读1936 评论9 喜欢35 Lollipop中有shared_element可以进行元素在activity之间进行共享,网上已经有很多介绍了,然而目前还有大量的kitkat设备,所以说啊,兼容更重要。 如下的方法,可以实现在旧的手机上实现动画效果。采用了类似于豌豆荚的开眼项目使用的技术。github上可能有在5.0以下的兼容包,... 阅读全文
posted @ 2016-08-29 23:30 马骝 阅读(2456) 评论(0) 推荐(0)
摘要: Android在加载大背景图或者大量图片时,经常导致内存溢出(Out of Memory Error),本文根据我处理这些问题的经历及其它开发者的经验,整理解决方案如下(部分代码及文字出处无法考证): 方案一、读取图片时注意方法的调用,适当压缩 尽量不要使用setImageBitmap或setIma 阅读全文
posted @ 2016-08-26 22:15 马骝 阅读(2469) 评论(0) 推荐(0)
摘要: 一言以蔽之:LeakCanary是一个傻瓜化并且可视化的内存泄露分析工具 为什么需要LeakCanary? 因为它简单,易于发现问题,人人可参与。 简单:只需设置一段代码即可,打开应用运行一下就能够发现内存泄露。而MAT分析需要Heap Dump,获取文件,手动分析等多个步骤。 易于发现问题:在手机端即可查看问题即引用关系,而MAT则需要你分析,找到Path To GC Ro... 阅读全文
posted @ 2016-08-18 22:43 马骝 阅读(1218) 评论(0) 推荐(0)
摘要: onCreate(){ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } onStop(){ getWindow().removeFlags(WindowManager.LayoutParams.FLAG_ 阅读全文
posted @ 2016-08-13 01:01 马骝 阅读(479) 评论(0) 推荐(0)
摘要: http://blog.csdn.net/lancees/article/details/8477513 蓝斯 DLNA一、DLNA简介 DLNA成 立于2003年6月24日,其前身是DHWG(Digital Home Working Group 数字家庭工作组),由Sony、Intel、Micro 阅读全文
posted @ 2016-08-09 00:30 马骝 阅读(1882) 评论(0) 推荐(0)
摘要: 旋转 阅读全文
posted @ 2016-07-28 22:52 马骝 阅读(124) 评论(0) 推荐(0)
点击右上角即可分享
微信分享提示