java操作文件(压缩文件,导出zip,删除zip,写入文件,读取文件)

    //压缩文件(防止中文乱码----使用apache的ZipOutputStream包)
    private static void writeZip(String[] strs,String zipname,String temppath) throws IOException {
        String[] files = strs;
        OutputStream os = new BufferedOutputStream(new FileOutputStream(temppath+"//"+zipname));
        ZipOutputStream zos = new ZipOutputStream(os);
        byte[] buf = new byte[8192];
        int len;
        for (int i=0;i<files.length;i++) {  
            File file = new File(files[i]);
            if ( !file.isFile() ) continue;
            ZipEntry ze = new ZipEntry( file.getName() );
            zos.putNextEntry(ze);
            BufferedInputStream bis = new BufferedInputStream( new FileInputStream( file ) );
            while ( ( len = bis.read( buf ) ) > 0 ) {
                zos.write( buf, 0, len );
            }
            zos.closeEntry();
            bis.close();
        }
         zos.setEncoding("GBK");
         for(int i=0;i<files.length;i++){
           File file= new File(files[i]);
           file.delete();
        }
         zos.closeEntry();
         zos.close();
         os.close();
    }

/**   
     * 递归查找文件   
     * @param baseDirName  查找的文件夹路径   
     * @param targetFileName  需要查找的文件名   
     * @param fileList  查找到的文件集合   
     */    
    public static void findFiles(String baseDirName, String targetFileName, List fileList) {     
        
        File baseDir = new File(baseDirName);       // 创建一个File对象  
        if (!baseDir.exists() || !baseDir.isDirectory()) {  // 判断目录是否存在  
            System.out.println("文件查找失败:" + baseDirName + "不是一个目录!");  
        }  
        String tempName = null;     
        //判断目录是否存在     
        File tempFile;  
        File[] files = baseDir.listFiles();  
        for (int i = 0; i < files.length; i++) {  
            tempFile = files[i];  
            if(tempFile.isDirectory()){  
                findFiles(tempFile.getAbsolutePath(), targetFileName, fileList);  
            }else if(tempFile.isFile()){  
                tempName = tempFile.getName();  
                if(wildcardMatch(targetFileName, tempName)){  
                    // 匹配成功,将文件名添加到结果集  
                    fileList.add(tempFile.getAbsoluteFile());  
                }  
            }  
        }  
    }    

/**
     * 删除zip
     */
    public void deleteZip(String path) {
       /* String[] sos = abpath.split("/");
        String name = ss[ss.length - 1];
        String path = abpath.replace("/" + name, "");*/

        File file = new File(path);// 里面输入特定目录
        File temp = null;
        File[] filelist = file.listFiles();
        for (int i = 0; i < filelist.length; i++) {
            temp = filelist[i];
            if (temp.getName().endsWith("zip"))// 获得文件名,如果后缀为“”,这个你自己写,就删除文件
            {
                temp.delete();// 删除文件}
            }
        }
    }

 

导出zip

 Date now = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");//可以方便地修改日期格
                String tm= dateFormat.format(new Date());
                String zipname=tm+".zip";
                writeZip(fils,zipname,temppath);//服务端生成zip文件
                InputStream in =  in = new FileInputStream(temppath+"//"+zipname); //获取文件的流  
                OutputStream os = response.getOutputStream();
                int len = 0;  
                byte buf[] = new byte[1024];//缓存作用
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/octet-stream; charset=UTF-8");
                response.addHeader("Content-Disposition", "attachment; filename=\""+new       String(zipname.getBytes("GB2312"),"ISO8859-1")+"\";");//
                os = response.getOutputStream();//输出流  
                while( (len = in.read(buf)) > 0 ) //切忌这后面不能加 分号 ”;“  
                 {  
                     os.write(buf, 0, len);//向客户端输出,实际是把数据存放在response中,然后web服务器再去response中读取  
                  }
                in.close();
                os.close();
                deleteZip(temppath);//导出后删除zip

 /**
     * 追加文件:使用FileWriter---写入
     */
    public static void appendMethodB(String fileName, StringBuffer content) {
        try {
            //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(fileName, true);
            /*OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileName, true),"UTF-8");
            osw.write(content);
            osw.close();*/
            
            writer.write(content.toString());
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 /**
     * 功能:Java读取txt文件的内容
     * 步骤:1:先获得文件句柄
     * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
     * 3:读取到输入流后,需要读取生成字节流
     * 4:一行一行的输出。readline()。
     * 备注:需要考虑的是异常情况
     * @param filePath
     */
    public static ArrayList<String> readTxtFile(String filePath){
         ArrayList<String> readList = new ArrayList<String>();  
        try {
                String encoding="GBK";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ //判断文件是否存在
                    InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);//考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                   
                    String lineTxt = null;
                    while((lineTxt = bufferedReader.readLine()) != null){
                        readList.add(lineTxt);                        
                    }                  
                    read.close();
        }else{
            System.out.println("找不到指定的文件");
        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return readList;
    }

posted on 2016-07-12 09:20  静以修身!  阅读(13945)  评论(0编辑  收藏  举报

导航