Write with a buffer to the exact file size.

I know it has to be possible and probably a very simple way to make a 1 to 1 copy of a file using a buffer. Whenever I try this though, it always adds the entire buffer at the end of the file even when the buffer isn't full. To get around this I had to over complicate it and make it look messy. Any help would be appreciated. Here is what I had to do: BufferedOutputStream out =new BufferedOutputStream(new FileOutputStream(fileToWrite));

BufferedInputStream in =new BufferedInputStream(new FileInputStream(fileToRead));

byte[] buffer =newbyte[1024];

int i;

while((i = in.read(buffer)) != -1){

byte[] tmp;

if(i < 1024){

tmp =newbyte[i];

for(int x = 0;x < i;x++){

tmp[x] = buffer[x];

}

}else{

tmp = buffer;

}

out.write(tmp);

}

in.close();

out.close();

[1614 byte] By [drawimagea] at [2007-11-27 10:25:10]
# 1

Why not use this method?

http://java.sun.com/javase/6/docs/api/java/io/OutputStream.html#write(byte[],%20int,%20int)

BigDaddyLoveHandlesa at 2007-7-28 17:32:07 > top of Java-index,Java Essentials,Java Programming...
# 2

Thanks for the reply, I officially feel stupid now. Thanks for your help :)

drawimagea at 2007-7-28 17:32:07 > top of Java-index,Java Essentials,Java Programming...
# 3

Not to rub it in, but when copying from one file to another, there is no need to use buffered streams. Think about your code:

1. BufferedInputStream reads from the file system to its internal buffer.

2. Your code reads from that buffer to the buffer you provide.

3. Then your code writes from the buffer you provide to BufferedOutputStream's

internal buffer.

4. Finally, when the buffer is full, BufferedOutputStream writes to the file system.

Example:

http://www.exampledepot.com/egs/java.io/CopyFile.html

Also, check out copying using FileChannels. For larger files, it is faster:

http://www.exampledepot.com/egs/java.nio/File2File.html

BigDaddyLoveHandlesa at 2007-7-28 17:32:07 > top of Java-index,Java Essentials,Java Programming...
# 4

Okay, thanks again. Is FileChannel faster for all files or just larger files?

drawimagea at 2007-7-28 17:32:07 > top of Java-index,Java Essentials,Java Programming...
# 5

> Okay, thanks again. Is FileChannel faster for all

> files or just larger files?

I'll leave that to you to time. I seem to remember it didn't make must difference for files a few K long.

BigDaddyLoveHandlesa at 2007-7-28 17:32:07 > top of Java-index,Java Essentials,Java Programming...
# 6

Alright, thanks again for your help, I'll try this out.

drawimagea at 2007-7-28 17:32:07 > top of Java-index,Java Essentials,Java Programming...