使用迭代器模式和组合模式实现浏览器一键导出下载为zip压缩包文件
由于项目需要,于是又想起之前看过的设计模式,于是便有了一键导出的想法。
思路简单明了。一步一步看下去就好。
<强> 1。创建组合对象强>
公共抽象类FileComponent {/* * *描述:递归创建文件夹,或者文件 */公共空间mkFile () { 抛出UnsupportedOperationException()方式; }/* * *描述:获取文件输入路径 */公共字符串getInPath () { 抛出UnsupportedOperationException()方式; }/* * *描述:获取文件输出路径 */公共字符串getOutPath () { 抛出UnsupportedOperationException()方式; }/* * *描述:对于文件夹来说是可以将其添加他文件夹或者文件 */公共空间添加(FileComponent FileComponent) { 抛出UnsupportedOperationException()方式; } } >之前此组合对象,可以是文件夹对象,也可是具体的文件对象,再后面调用中,不需要了解到底是一个文件夹还是一个文件(即组合模式的透明性)。
<强> 2。组合对象抽象类的实现强>
上述抽象类的实现如下:
公开课ZipFileItem延伸FileComponent {//输入文件的路径 字符串inPath;//输出文件的路径 字符串outPath;//子节点文件信息 ListfileComponents=new ArrayList ();//inPath可以为null 公共ZipFileItem(字符串outPath) { 这一点。outPath=outPath; }//压缩文件的源目录路径和压缩好的目标位置 inPath公共ZipFileItem(字符串,字符串outPath) { 这一点。inPath=inPath; 这一点。outPath=outPath; } 公共空间添加(FileComponent FileComponent) { fileComponents.add (fileComponent); } 公共空间删除(FileComponent FileComponent) { fileComponents.remove (fileComponent); } @Override 公共字符串getInPath () { 返回inPath; } @Override 公共字符串getOutPath () { 返回outPath; } @Override 公共空间mkFile () { FileUtils。它仅仅(inPath outPath); Iterator 迭代器=fileComponents.iterator ();//如果是文件夹,那么还可以迭代文件及对象中的具体文件对象 而(iterator.hasNext ()) { FileComponent FileComponent=iterator.next (); fileComponent.mkFile (); } } } <强> 3。文件工具类强>
公开课ConferenceFileUtils {/* * *描述:根据文件的绝对路径,在绝对的输出路径进行创建文件 * @param inPath输入路径,如果是要根据已有的文件来创建,那么一定要传 * @param outPath输出路径,如果是目录则不用 */inPath公共静态空它仅仅(字符串,字符串outPath) { 文件fileIn=新文件(inPath); 文件fileOut=新文件(outPath);//如果目标文件已存在,则忽略,如果文件不存在。则进行创建 如果(! fileOut.exists ()) { int lastSeparator=outPath.lastIndexOf (File.separator); 字符串lastPart=outPath.substring (lastSeparator);//如果不是文件夹,则创建文件 如果(lastPart.lastIndexOf (“。”) !=1) { LoggerUtil.info(“- - - - - - - - - - -让concreteFile - - - - - - - - - -”+ outPath); FileInputStream=零; FileOutputStream=零; 文件目录=零; 尝试{ 目录(outPath=新文件。substring (0, lastSeparator + 1)); directory.mkdirs ();=新FileOutputStream (fileOut);//如果源文件存在 如果(fileIn.exists ()) { 在新FileInputStream=(fileIn); int len; byte [] buf=新字节[10240]; 而((len=in.read (buf))在0){ out.write (buf 0 len); } out.close (); in.close (); 在=零; } }捕捉(IOException e) { System.err。println(“创建文件失败!”,e); } }//如果是文件夹则创建文件夹,如果父类文件夹不存在,那么也创建 其他{ System.err。println(“- - - - - - - - - - -目录- - - - - - - - - -”+ outPath); fileOut.mkdirs (); } } }//递归删除文件夹以及文件 公共静态布尔deleteDir(文件dir) { 如果(dir.isDirectory ()) { String[]的孩子=dir.list ();//递归删除目录中的子目录 for (int i=0;i0) { 出去了。写(src, 0, len); } out.flush (); out.close (); in.close (); }捕捉(IOException e) { 把新的IOException (e); 最后}{ 如果(零!=){ FortifyUtil.commonReleasedResource(出); } 如果(零!=){ FortifyUtil.commonReleasedResource(的); } } } } Java后台实现浏览器一键导出下载压缩压缩包