1 package rydeen.io;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.ArrayList;
6 import java.util.Iterator;
7 import java.util.List;
8
9 import rydeen.ProcessTarget;
10 import rydeen.TargetSource;
11
12
13
14
15
16
17
18
19
20 public class DirectoryTargetSource implements TargetSource{
21 private File file;
22
23
24
25
26
27
28
29
30
31 public DirectoryTargetSource(File file) throws IOException{
32 if(file == null){
33 throw new NullPointerException();
34 }
35 if(!file.isDirectory()){
36 throw new IOException(file.getName() + ": not directory");
37 }
38 this.file = file;
39 }
40
41
42
43
44 @Override
45 public String getName(){
46 return file.getPath();
47 }
48
49
50
51
52 @Override
53 public Iterator<ProcessTarget> iterator(){
54 final List<File> list = new ArrayList<File>();
55 listFiles(list, file);
56
57 return new Iterator<ProcessTarget>(){
58 private Iterator<File> iterator = list.iterator();
59
60 @Override
61 public boolean hasNext(){
62 return iterator.hasNext();
63 }
64
65 @Override
66 public ProcessTarget next(){
67 File target = iterator.next();
68 String name = target.getPath();
69 name = name.substring(file.getPath().length());
70 if(name.startsWith(File.separator)){
71 name = name.substring(1);
72 }
73 name = name.replace(File.separatorChar, '/');
74
75 return new FileProcessTarget(DirectoryTargetSource.this, name, target);
76 }
77
78 @Override
79 public void remove(){
80 }
81 };
82 }
83
84
85
86
87 @Override
88 public boolean contains(String target){
89 File targetFile = new File(file, target);
90 return targetFile.exists();
91 }
92
93
94
95
96 public void close(){
97
98 }
99
100 private void listFiles(List<File> list, File base){
101 if(base.isDirectory()){
102 File[] files = base.listFiles();
103 for(File file: files){
104 listFiles(list, file);
105 }
106 }
107 else{
108 list.add(base);
109 }
110 }
111 }