Ierator 모드 및 조합 모드를 사용하여 브라우저에서 압축 패키지 파일을 지퍼하기 위해 한 번의 클릭 내보내기를 구현하고 다운로드하십시오.
프로젝트의 요구로 인해 이전에 본 디자인 패턴을 기억 했으므로 한 번의 클릭 수출에 대한 아이디어가있었습니다.
아이디어는 간단하고 명확합니다. 단계별로 시청하십시오.
1. 복합 객체를 만듭니다
공개 초록 클래스 FileComponent { / ** * 설명 : 재귀 적으로 폴더 또는 파일을 생성 * / public void mkfile () {throw new new UnsupportedOperationException (); } / ** * 설명 : 파일 입력 경로 가져옵니다 * / public string getInpath () {새로운 UnsupportedOperationException (); } / ** * 설명 : 파일 출력 경로 가져옵니다 * / public string getoutPath () {새 UnsupportedOperationException (); } / *** 설명 : 폴더의 경우 다른 폴더 또는 파일을 추가 할 수 있습니다* / public void add (filecomponent filecomponent) {wrach new unsupportedOperationException (); }}이 조합 객체는 폴더 객체 또는 특정 파일 객체 일 수 있습니다. 후속 호출에서 폴더인지 파일인지 (즉, 조합 모드의 투명성)를 알 필요가 없습니다.
2. 복합 객체 추상 클래스의 구현
위의 추상 클래스의 구현은 다음과 같습니다.
public class zipfileitem은 filecomponent {// 입력 파일 문자열의 경로를 확장합니다. // 출력 파일의 경로 String OutPath; // 서브 노드 파일 정보 목록 <FilEcomponent> filecomponents = new ArrayList <FileComponent> (); // inpath는 null public ZipFileItem (String OutPath) {this.outpath = outPath; } // 압축 파일의 소스 디렉토리 경로 및 압축 대상 위치 public ZipFileItem (String inpath, String OutPath) {this.inpath = inpath; this.outpath = OutPath; } public void add (filecomponent filecomponent) {filecomponents.add (filecomponent); } public void remove (filecomponent filecomponent) {filecomponents.remove (filecomponent); } @override public String getInpath () {return inpath; } @override public string getoutpath () {return outpath; } @override public void mkfile () {fileUtils.createFile (inpath, OutPath); iterator <filecomponent> iterator = filecomponents.iterator (); // 폴더 인 경우 객체의 파일과 특정 파일 객체를 반복 할 수도 있습니다. filecomponent.mkfile (); }}}3. 파일 도구 클래스
Public Class ConferenceFileUtils { /** * 설명 : 파일 * @param inpath 입력 경로의 절대 경로를 기반으로 절대 출력 경로에서 파일을 만듭니다. 기존 파일을 기반으로 작성하려면 * @Param OutPath 출력 경로를 통과해야합니다. 디렉토리 인 경우 */ public static void createFile (String inpath, String OutPath) {file fileIn = new File (inpath)을 사용하지 않습니다. 파일 파일 아웃 = 새 파일 (OutPath); // 대상 파일이 이미 존재하면 파일이 존재하지 않으면 무시하십시오. 그런 다음 if (! fileout.exists ()) {int lastseparator = outpath.lastIndexof (file.separator)를 작성합니다. String lastPart = OutPath.Substring (LastSeparator); // 폴더가 아닌 경우 파일을 만듭니다. fileInputStream in = null; fileoutputStream out = null; 파일 디렉토리 = null; try {directory = 새 파일 (OutPath.SubString (0, lastseparator+1)); directory.mkdirs (); out = new FileOutputStream (파일 아웃); // 소스 파일이 존재하는 경우 (filein.exists ()) {in = new FileInputStream (fileIn); int len; 바이트 [] buf = 새로운 바이트 [10240]; while ((len = in.read (buf))> 0) {out.write (buf, 0, len); } out.close (); 넣다(); in = null; }} catch (ioexception e) {System.err.println ( "파일 생성 실패!", e); }} // 폴더 인 경우 폴더를 만듭니다. 부모 클래스 폴더가 존재하지 않으면 else {를 만듭니다. System.err.println("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Boolean 성공 = DIR, children [i]); innult {reption int. } catch (ioexception e) {new infection (null! = out) {null! = in);4. 코어 내보내기 논리 코드
공개 클래스 ExportMaterialToZiptEMPlate {@Resource Private EnrichFilELevelsService EnrichFilELevelsService; // 루트 디렉토리 폴더 이름 또는 다운로드 브라우저 파일 이름 개인 문자열 downloadzipname; // 루트 디렉토리 주소 개인 문자열 savepath = "d : // tempfile"; // 루트 디렉토리 경로 비공개 문자열 superRootPath; // 루트 디렉토리 객체 개인 filecomponent suproot; // 비즈니스 매개 변수 dto private exportallthematerialDto paramdto; // 응답 개인 httpservletResponse 응답; public exportMaterialToZiptEMPLATE (ExportAllTheMaterialDto Paramdto, EnrichFilevelsService EnrichFilleEvelsService, httpservletResponse 응답) {this.DownloadZipName = paramdto.getDownLoadZipName (); this.paramdto = paramdto; this.response = 응답; this.enrichfilevelsservice = EnrichfilelevelsService; this.superRootPath = SavePath+file.separator+downloadzipname; this.superroot = new ZipFileItem (SuperRootPath); } // 1. 루트 디렉토리 Private void enrichfileLevels () {EnrichfilelevelsService.enrichfileLevels (SuperRoot, SuperRootPath, Paramdto); } // 2. 파일 디렉토리 레벨을 생성, 즉 모든 파일 (폴더 포함) 개인 void createAlteFiles () {if (null! = superRoot) {superRoot.mkFile (); }} // 3. 파일 레벨을 생성 한 후 압축 한 후 압축 한 후 브라우저 개인 void compressanddownload () {file srcfile = new File (orpotifyUtil.filterfilename (superRootPath))에 다운로드하십시오. 문자열 targetFilePath = SavePath+file.separator+srcfile.getName ()+". Zip"; 파일 targetfile = 새 파일 (orpotifyutil.filterfilename (TargetFilePath)); zipfileutil.zipfiles (srcfile, targetfile); 시도 {// 파일을 압축하여 임시 경로 문자열 downfilename = downloadzipname+". zip"; response.reset (); // 출력 유형을 정의합니다. response.setheader ( "content-disposition", "attachment; filename =" + new String (downfilename.getBytes ( "gbk"), "iso-8859-1") + "; size =" + targetfile.length ()); outputfileutil.outputfile (TargetFile, 응답); // if (srcfile.exists ()) {conferenceFileUtils.deletedir (srcfile); } // 임시 압축 패키지를 삭제하면 (targetFile.Exists ()) {targetFile.Delete (); }} catch (ioexception e) {devlog.error (e.getMessage ()); }} // 한 클릭 내보내기, 외관 모드 public void export () {enrichfilelevels (); CreateAllThefiles (); compressanddownload (); }}5. 파일 레벨 인터페이스를 풍부하게합니다
공개 인터페이스 EnrichFilELEVELSSERVICE {public void enrichfileLevels (filecomponent super root, String SuperRootPath, ExportAllTheMaterialDto Paramdto);} 다른 비즈니스 시나리오에서는이 인터페이스를 구현하고 EnrichFilelevels () 메소드를 구현하고,이 인터페이스를 ExportMaterialToziptEmplate 클래스의 생성자 메소드로 구현하는 클래스 인스턴스를 전달한 다음 ExportMaterialToZiptEmplate Class 인스턴스의 Export () 메소드를 호출하십시오. 지금 바로
새로운 ExportMaterialToZiptemplate (dtoparams,
EnrichFilELevelsService, responsk) .export ();
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.