/
LazyFileOutputStream.java
95 lines (76 loc) · 2.21 KB
/
LazyFileOutputStream.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package org.pollerosoftware.file;
import java.io.*;
/**
* This class inherit from OutputStream and wraps a standard FileOutputStream
* to simply create a lazy initialized FileOutputStream, instead of creating
* the file when the constructor is called, it creates the file only when
* it is really need(when some writing operation happens).
*
* @author Alessio Pollero
* @version 1.0
*/
public class LazyFileOutputStream extends OutputStream {
protected File file;
protected boolean append;
protected Object streamLock = new Object();
protected boolean streamOpen = false;
private FileOutputStream oStream;
//Constructors
public LazyFileOutputStream(File f) {
this.file = f;
}
public LazyFileOutputStream(File f, boolean append) {
this.file = f;
this.append = append;
}
public LazyFileOutputStream(String name) {
this(name != null ? new File(name) : null);
}
public LazyFileOutputStream(String name, boolean append) {
this(name != null ? new File(name) : null, append);
}
//Methods implementation
/**
* This method is the key component of the class, it gets
* the wrapped FileOutputStream object if already initialized
* or if not it generates it in a thread safe way.
* This kind of implementation allows to call the initialization
* of the underlying FileOutputStream object only when needed.
*
* @return the wrapped FileOutputStream object
* @throws FileNotFoundException if the file can't be created
*/
protected FileOutputStream outputStream() throws FileNotFoundException {
synchronized (streamLock) {
if(!streamOpen) {
oStream = new FileOutputStream(file, append);
streamOpen = true;
}
}
return oStream;
}
@Override
public void close() throws IOException {
super.close();
if(streamOpen)
outputStream().close();
}
@Override
public void flush() throws IOException {
super.flush();
if(streamOpen)
outputStream().flush();
}
@Override
public void write(int b) throws IOException {
outputStream().write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
outputStream().write(b, off, len);
}
@Override
public void write(byte[] b) throws IOException {
outputStream().write(b);
}
}