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;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM