Reputation: 15117
I have the following code, but I'm not sure that i'm doing everything correctly in terms of efficiency/flushing/closing streams. Some advice would greatly help, thank you
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file, true));
byte[] buf = new byte[32 * 1024]; // should this be 32KB?
while ((in.read(buf)) > 0) {
out.write(buf);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Upvotes: 0
Views: 3089
Reputation: 33
Your code seems ok from a "does it work" perspective... However you could make is look "prettier" by using a try with resource. Try with Resources Your provided code will essentially turn into the following:
try(OutputStream out = new BufferedOutputStream(new FileOutputStream(file, true)) {
byte[] buf = new byte[1024];
while ((in.read(buf)) > 0) {
out.write(buf);
}
out.flush();
}
This is a Java7 feature, and if the stream resource implements java.lang.AutoCloseable then it will be closed automatically.
Depending on what your trying to do, something along the lines of the following may be a simpler solution?
PrintStream p = new PrintStream(new BufferedOutputStream(new FileOutputStream(aFile, true)));
Upvotes: 1
Reputation: 533640
The most important issue you have is that you are ignoring how many bytes you read.
for(int len; (len = in.read(buf)) > 0;)
out.write(buf, 0, len);
If you don't use the length you are assuming you will always read exactly 32 KB, this is a big assumption.
Buffers are useful when you have lots of small writes.
The default buffered size for BufferedOutputStream is 8 KB and if your writes are much smaller than this i.e. < 512 bytes they can really help.
However, if you are writing say 32 KB they are probably doing nothing, or not helping. I would take them out.
BTW, without a buffer, you don't need to call flush();
BTW2
KB = 1024 bytes
kB = 1000 bytes
Kb = 1024 bits
kb = 1000 bits.
Upvotes: 2