我写这个例子只是想练习组合模式和迭代器模式的使用,模仿了headfirst设计模式的写法,解决了里面的bug,自己mark一下,对于java初学者不是好理解,so~多看几遍总归有些收获,高手就轻拍吧...
package com.alex.component;
import java.util.Iterator;
@SuppressWarnings("rawtypes")
public abstract class AbstractFile{
public String getFileName() {
throw new UnsupportedOperationException();
}
public String getFileType() {
throw new UnsupportedOperationException();
}
public void setFileType(String fileType) {
throw new UnsupportedOperationException();
}
public void add(AbstractFile abstractFile){
throw new UnsupportedOperationException();
}
public void remove(AbstractFile abstractFile){
throw new UnsupportedOperationException();
}
public AbstractFile getChild(int i){
throw new UnsupportedOperationException();
}
public void print(){
throw new UnsupportedOperationException();
}
public boolean isSelectedFile(String[] configs){
throw new UnsupportedOperationException();
}
public abstract Iterator createIterator();
public boolean isNotTheSelectedFile(String[] configs){
throw new UnsupportedOperationException();
}
}
package com.alex.component;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.alex.iterator.DirectoryCompositeIterator;
@SuppressWarnings("rawtypes")
public class DirectoryComposite extends AbstractFile {
private List list = new ArrayList();;
private String fileName;
private String fileType;
public DirectoryComposite(String fileName,String fileType) {
this.fileName=fileName;
this.fileType=fileType;
}
@Override
public String getFileName() {
return fileName;
}
@Override
public String getFileType() {
return fileType;
}
@Override
public void add(AbstractFile abstractFile) {
list.add(abstractFile);
}
@Override
public void remove(AbstractFile abstractFile) {
list.remove(abstractFile);
}
@Override
public AbstractFile getChild(int i) {
return (AbstractFile)list.get(i);
}
@Override
public void print() {
System.out.println(getFileName()+","+getFileType());
System.out.println("-------------------------");
/* Iterator iterator=list.iterator();
while(iterator.hasNext()){
AbstractFile abstractFile=(AbstractFile)iterator.next();
abstractFile.print();
}*/
}
@Override
public Iterator createIterator() {
// return new DirectoryCompositeIterator(list.iterator());
return list.iterator();
}
@Override
public boolean isSelectedFile(String[] configs){
for(String config:configs){
if(getFileName().indexOf(config)!=-1){
return true;
}
}
return false;
}
}
package com.alex.component;
import java.util.Iterator;
import com.alex.iterator.FileLeafIterator;
@SuppressWarnings("rawtypes")
public class FileLeaf extends AbstractFile{
private String fileName;
private String fileType;
public FileLeaf(String fileName, String fileType) {
this.fileName = fileName;
this.fileType = fileType;
}
@Override
public String getFileName() {
return fileName;
}
@Override
public String getFileType() {
return fileType;
}
@Override
public void remove(AbstractFile abstractFile) {
super.remove(abstractFile);
}
@Override
public void setFileType(String fileType){
this.fileType=fileType;
}
@Override
public void print() {
System.out.println(" "+getFileName());
System.out.println(" --"+getFileType());
}
@Override
public Iterator createIterator() {
return new FileLeafIterator();
}
@Override
public boolean isSelectedFile(String[] configs){
for (String config : configs) {
if(getFileName().indexOf(config)!=-1){
return true;
}
}
return false;
}
@Override
public boolean isNotTheSelectedFile(String[] configs) {
for (String config : configs) {
if(getFileName().indexOf(config)!=-1){
return false;
}
}
return true;
}
}
package com.alex.iterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;
import com.alex.component.AbstractFile;
import com.alex.component.DirectoryComposite;
@SuppressWarnings("rawtypes")
public class DirectoryCompositeIterator implements Iterator {
private final Stack stack=new Stack();
@SuppressWarnings("unchecked")
public DirectoryCompositeIterator(Iterator iterator){
stack.push(iterator);
}
@Override
public boolean hasNext() {
if(stack.empty()){
return false;
}else{
Iterator iterator=(Iterator)stack.peek();
if(!iterator.hasNext()){
stack.pop();
return hasNext();
}else{
return true;
}
}
}
@SuppressWarnings("unchecked")
@Override
public Object next() {
if(hasNext()){
Iterator iterator = (Iterator)stack.peek();
AbstractFile abstractFile = (AbstractFile)iterator.next();
if(abstractFile instanceof DirectoryComposite){
stack.push(abstractFile.createIterator());
}
return abstractFile;
}else{
return new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
package com.alex.iterator;
import java.util.Iterator;
import java.util.Stack;
@SuppressWarnings("rawtypes")
public class FileLeafIterator implements Iterator{
@Override
public boolean hasNext() {
return false;
}
@Override
public Object next() {
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
package com.alex.print;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.alex.component.AbstractFile;
import com.alex.component.DirectoryComposite;
import com.alex.iterator.DirectoryCompositeIterator;
import com.alex.util.FileUtils;
import com.alex.util.SystemConstantValue;
@SuppressWarnings("rawtypes")
public class PrintToExcel {
private AbstractFile abstractFile;
public PrintToExcel(AbstractFile abstractFile) {
this.abstractFile = abstractFile;
}
private List iteratorAbstractFile(AbstractFile abstractFile,Map filters) {
//get filters
String[] dirFilters=getFilterString(filters, "dirFilters");
String[] fileFilters=getFilterString(filters, "fileFilters");
String[] keyFeathers=getFilterString(filters, "keyFeathers");
Iterator iterator=new DirectoryCompositeIterator(abstractFile.createIterator());
List absList=new ArrayList();
while(iterator.hasNext()){
AbstractFile absFile=(AbstractFile)iterator.next();
try {
if(absFile!=null){
//1.获取path
String path=absFile.getFileName().substring(0,absFile.getFileName().lastIndexOf(File.separator));
File tempFile=new File(path);
AbstractFile dirFile=new DirectoryComposite(FileUtils.getAbstractFilePath(tempFile),FileUtils.getFileType(tempFile));
if(dirFile.isSelectedFile(dirFilters)){
if(absFile.isNotTheSelectedFile(fileFilters)){
absList.add(FileUtils.changeTheFileType(absFile,keyFeathers));
}
}
}
} catch (UnsupportedOperationException e) {
}
}
return absList;
}
public static String[] getFilterString(Map filtersMap,String key){
validateParams(filtersMap,key);
if(filtersMap.containsKey(key)){
return (String[])filtersMap.get(key);
}
return null;
}
public void print(){
Iterator iterator=new DirectoryCompositeIterator(abstractFile.createIterator());
while(iterator.hasNext()){
try {
AbstractFile absFile=(AbstractFile)iterator.next();
absFile.print();
} catch (UnsupportedOperationException e) {
}
}
}
public void printToExcel(Map filters){
List absList=iteratorAbstractFile(abstractFile,filters);
HSSFWorkbook wb=new HSSFWorkbook();
HSSFSheet sheet=wb.createSheet("文件数据");
HSSFRow row0=sheet.createRow(0);
HSSFCell cell0=row0.createCell(0);
cell0.setCellValue(SystemConstantValue.CELL_FILE_NAME);
cell0=row0.createCell(1);
cell0.setCellValue(SystemConstantValue.CELL_FILE_TYPE);
for(int i=1,j=0;i filtersMap,String key) {
if(filtersMap.size()!=3){
throw new IllegalArgumentException("the filtersMap's size must is 3");
}
for(String keyString:filtersMap.keySet()){
if(filtersMap.get(keyString)==null){
throw new NullPointerException("the filters is null");
}
}
if(key==null){
throw new NullPointerException("the key is null");
}
}
}
package com.alex.test;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.alex.component.AbstractFile;
import com.alex.print.PrintToExcel;
import com.alex.util.FileUtils;
public class TestFile {
public static void main(String[] args) {
//Map filters
Map filters=new HashMap();
filters.put("dirFilters", new String[]{"netstat"});
filters.put("fileFilters", new String[]{"txt"});
filters.put("keyFeathers", new String[]{"doc"});
String path="D:\\test";
File file=new File(path);
AbstractFile abstractFile=FileUtils.listFiles(file);
PrintToExcel pte=new PrintToExcel(abstractFile);
pte.printToExcel(filters);
pte.print();
}
}
package com.alex.util;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import com.alex.component.AbstractFile;
import com.alex.component.DirectoryComposite;
import com.alex.component.FileLeaf;
public class FileUtils {
public static String getFileType(File file){
if(file.isDirectory()){
return "Directory";
}
int dot=file.getName().lastIndexOf(".")+1;
String type=file.getName().substring(dot);
return type;
}
public static String getAbstractFilePath(File file){
return file.getAbsolutePath();
}
public static void validateListFilesParameters(File file){
if(!file.isDirectory()){
throw new IllegalArgumentException("Parameter 'directory' is not a directory");
}
}
public static AbstractFile innerListFiles(File directory,AbstractFile abstractFile){
if(directory.listFiles()!=null){
List founds = Arrays.asList(directory.listFiles());
if(founds!=null){
for(File found:founds){
if(found.exists()){
if(found.isDirectory()){
AbstractFile dirFile=new DirectoryComposite(getAbstractFilePath(found),getFileType(found));
abstractFile.add(dirFile);
innerListFiles(found,dirFile);
}else{
AbstractFile fileLeaf=new FileLeaf(getAbstractFilePath(found),getFileType(found));
abstractFile.add(fileLeaf);
}
}
}
}
}
return abstractFile;
}
public static AbstractFile listFiles(File directory){
validateListFilesParameters(directory);
String fileName=getAbstractFilePath(directory);
String fileType=getFileType(directory);
AbstractFile topPath=new DirectoryComposite(fileName, fileType);
//1.listFile
innerListFiles(directory,topPath);
return topPath;
}
public static AbstractFile changeTheFileType(AbstractFile abstractFile,String[] filters){
if(abstractFile instanceof FileLeaf){
if(abstractFile.isSelectedFile(filters)){
abstractFile.setFileType(SystemConstantValue.FILE_DOC);
}else{
abstractFile.setFileType(SystemConstantValue.FILE_UPLOAD);
}
}
return abstractFile;
}
}
package com.alex.util;
public class SystemConstantValue {
public static String CELL_FILE_NAME="文件名";
public static String CELL_FILE_TYPE="介质形式";
public static String FILE_PATH="output/output.xls";
public static String FILE_DOC="文档";
public static String FILE_UPLOAD="提交物";
}