文件操作

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

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

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

/.nomedia

[java] view plain copy
  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
 
   

 

 

 


转载于:https://www.cnblogs.com/maliu/p/6505408.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值