1 package rydeen.io;
2
3 import rydeen.Destination;
4 import rydeen.ProcessTarget;
5
6 import java.io.File;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.OutputStream;
10
11 /**
12 * ディレクトリを出力先とする{@link Destination <code>Destination</code>}の実装クラスです.
13 *
14 * @author Haruaki Tamada
15 */
16 public class DirectoryDestination extends AbstractDestination{
17 private File base;
18
19 /**
20 * 基準となるディレクトリを指定してオブジェクトを構築します.
21 * もし,baseが存在し,ディレクトリでない場合はIOExceptionが投げられます.
22 * baseが存在しなかった場合は,適切なタイミングでディレクトリが作成されます.
23 */
24 public DirectoryDestination(File base) throws IOException{
25 if(base.exists() && !base.isDirectory()){
26 throw new IOException(base + ": not directory");
27 }
28 this.base = base;
29 }
30
31 /**
32 * <p>
33 * 引数で与えられた文字列に出力するための出力ストリームを作成して,返します.
34 * </p><p>
35 * 引数にFile.separatorが含まれていれば,ディレクトリ階層として扱われます.
36 * ディレクトリが存在しない場合は,自動的に作成されます.
37 * </p><p>
38 * ディレクトリ作成に失敗した場合はIOExceptionが投げられます.
39 * 引数にnullが与えられた場合はNullPointerExceptionが投げられます.
40 * </p>
41 *
42 * @param name 出力先のファイル名.
43 * @throws IOException ディレクトリ作成に失敗した場合
44 */
45 @Override
46 public OutputStream getOutput(String name) throws IOException{
47 if(name == null){
48 throw new NullPointerException();
49 }
50 File file = new File(base, name);
51 File parent = file.getParentFile();
52 if(!parent.exists()){
53 boolean flag = parent.mkdirs();
54 if(!flag){
55 throw new IOException(parent.getPath() + ": mkdir failed");
56 }
57 }
58 return new FileOutputStream(file);
59 }
60
61 /**
62 * <p>
63 * 引数で与えられたProcessTargetを出力するための出力ストリームを作成して,返します.
64 * </p><p>
65 * targetの{@link ProcessTarget#getName <code>getName</code>}
66 * メソッドで得られる文字列をもとに出力先が決められます.
67 * その文字列にFile.separatorが含まれていれば,ディレクトリ階層として扱われます.
68 * ディレクトリが存在しない場合は,自動的に作成されます.
69 * </p><p>
70 * ディレクトリ作成に失敗した場合はIOExceptionが投げられます.
71 * 引数にnullが与えられた場合はNullPointerExceptionが投げられます.
72 * </p>
73 *
74 * @param target 出力するProcessTarget.
75 * @throws IOException 既にcloseメソッドが呼ばれ,出力ストリームが閉じれているとき.
76 */
77 @Override
78 public OutputStream getOutput(ProcessTarget target) throws IOException{
79 if(target == null){
80 throw new NullPointerException();
81 }
82 return getOutput(target.getName());
83 }
84
85 /**
86 * 何も行いません.
87 */
88 @Override
89 public void close(){
90 }
91 }