1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sourceforge.javadpkg.io.impl;
20
21 import java.io.File;
22 import java.io.FileNotFoundException;
23 import java.io.IOException;
24 import java.io.OutputStream;
25
26 import net.sourceforge.javadpkg.io.DataTarget;
27 import net.sourceforge.javadpkg.io.Streams;
28
29
30
31
32
33
34
35
36
37 public class DataFileTarget implements DataTarget {
38
39
40
41 private File file;
42
43 private OutputStream out;
44
45
46
47
48
49
50 private UncloseableOutputStream publicOut;
51
52 private String name;
53
54 private boolean opened;
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71 public DataFileTarget(File file) {
72 super();
73
74 if (file == null)
75 throw new IllegalArgumentException("Argument file is null.");
76
77 this.file = file;
78 this.out = null;
79 this.publicOut = null;
80 this.name = file.getAbsolutePath();
81 this.opened = false;
82 }
83
84
85 @Override
86 public String getName() {
87 return this.name;
88 }
89
90
91
92
93
94
95
96
97 private void createPublicOutputStream() {
98 this.publicOut = new UncloseableOutputStream(this.out, new DelegateCloseHandler(this));
99 }
100
101
102
103
104
105
106
107
108
109
110
111 private void ensureOutputStream() throws IOException {
112 if (this.out == null) {
113 if (!this.opened) {
114 try {
115 this.out = Streams.createBufferedFileOutputStream(this.file);
116 } catch (FileNotFoundException e) {
117 throw new IOException("Couldn't open stream on target |" + this.name + "|: " + e.getMessage());
118 }
119 this.createPublicOutputStream();
120 } else
121 throw new IOException("The stream of target |" + this.name + "| is already closed.");
122 }
123 }
124
125
126 @Override
127 public OutputStream getOutputStream() throws IOException {
128 this.ensureOutputStream();
129 return this.publicOut;
130 }
131
132
133 @Override
134 public void close() throws IOException {
135 try {
136 if (this.out != null) {
137 this.out.close();
138 }
139 } finally {
140 this.publicOut = null;
141 this.out = null;
142 }
143 }
144
145 }