1. 策略模式 - strategy pattern/**
Strategy Pattern 使用参数args[](regular expression 正则表达式)决定所要读取的文件类型。 而不是在code中直接hard code。
*/
public class DirList3 {
public static void main(final String[] args) {
File path = new File("D:\\Users\\wpeng\\workspace\\Hello\\src\\think\\in\\java\\io");
String[] list;
if(args.length == 0){
list = path.list();
}else{
list = path.list(new FilenameFilter() {
private Pattern pattern = Pattern.compile(args[0]);
@Override
public boolean accept(File dir, String name) {
return pattern.matcher(name).matches();
}
});
}
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for(String dirItem : list){
System.out.println(dirItem);
}
}
}
2. 装饰者模式 - Decorator Pattern/**
* 装饰者模式 decorator pattern
* FileInputStearm -> FileRader -> BufferReader
* @author WPeng
* @since 2012-11-5
*/
public class BufferedInputFile {
// Throw exceptions to console
public static String read(String filename) throws IOException{
// Reading input by lines
BufferedReader in = new BufferedReader(new FileReader(filename));
String s;
StringBuilder sb = new StringBuilder();
while((s = in.readLine()) != null){
sb.append(s + "\n");
}
in.close();
return sb.toString();
}
public static void main(String[] args) throws IOException {
System.out.print(read("BufferedInputFile.java"));
// FileInputStream -> BufferedInputStream -> DataInputStream
DataInputStream in =
new DataInputStream(
new BufferedInputStream(
new FileInputStream("FormattedMemoryInput.java")));
while(true){
System.out.print((char)in.readByte());
}
}
}
3. 模板模式 Template patternpublic class MappedIO {
private static int numOfInts = 4000000;
private static int numOfUbuffInts = 200000;
private abstract static class Tester{
private String name;
public Tester(String name){
this.name = name;
}
public void runTest(){
System.out.print(name + ": ");
try {
long start = System.nanoTime();
test();
double duration = System.nanoTime() - start;
System.out.format("%.2f\n", duration/1.0e9);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public abstract void test() throws IOException;
}
private static Tester[] tests = {
new Tester("Stream Write") {
@Override
public void test() throws IOException {
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(new File("temp.tmp"))));
for(int i=0; i<numOfInts; i++){
dos.writeInt(i);
}
dos.close();
}
},
new Tester("Mapped Write") {
@Override
public void test() throws IOException {
FileChannel fc = new RandomAccessFile("temp.tmp", "rw").getChannel();
IntBuffer ib = fc.map(
FileChannel.MapMode.READ_WRITE, 0, fc.size()).asIntBuffer();
for(int i=0; i<numOfInts; i++){
ib.put(i);
}
fc.close();
}
}
};
public static void main(String[] args) {
for(Tester test : tests){
test.runTest();
}
}
}