Copy File, too easy?

B

Berlin Brown

Is there anything wrong with this copy file code. Just seems I should
be doing something more? I dont need to worry about the max size of
the file or anything?

public static void copyFile(String fromFile, String toFile) {

BufferedInputStream bi = new BufferedInputStream(new
FileInputStream(new File(fromFile)));
BufferedOutputStream bo = new BufferedOutputStream(new
FileOutputStream(new File(toFile)));

while(true) {
byte l = bi.read();
if (l == -1)
break;

bo.write(l);
bo.close();
bi.close();
} /// end of the while ///

return;

} /// end of the method //
 
M

Mike Schilling

Berlin Brown said:
Is there anything wrong with this copy file code. Just seems I should
be doing something more? I dont need to worry about the max size of
the file or anything?

public static void copyFile(String fromFile, String toFile) {

BufferedInputStream bi = new BufferedInputStream(new
FileInputStream(new File(fromFile)));
BufferedOutputStream bo = new BufferedOutputStream(new
FileOutputStream(new File(toFile)));

while(true) {
byte l = bi.read();
if (l == -1)
break;

bo.write(l);
bo.close();
bi.close();
} /// end of the while ///

return;

} /// end of the method //



read() returns an int, not a byte. It needs, after all, to be able to
disinguish the -1 which means end-of-file from all possible byte values.

And you want the "close()"s outside the loop body.

And it's not particularly efficient; you'd do better to read and write in
bigger chunks.

And clearly you've never compiled this, because the potential IOExceptions
aren't either being handled or declared to escape the method.

And you should do something in the way of error handling.
 
C

Chris Uppal

Mike said:
And it's not particularly efficient; you'd do better to read and write in
bigger chunks.

It's not particularly /inefficient/ either. In fact the difference is pretty
trivial (given that the code is, very properly, using buffered streams).

Messing around with byte[] arrays adds complexity, and comes under the general
header of "optimisation" and, as such, is normally something you only do in
order to fix an actual, measurable, performance problem. (Or so the Standard
Advice goes, anyway ;-)

-- chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,270
Messages
2,571,102
Members
48,773
Latest member
Kaybee

Latest Threads

Top