/*** Copy (byte stream) of any file with the buffer function (buffer size 8 K) * @ author mjn * @ date 2011-10-03 */public class filecopywithbuffer {public static void main (string [] ARGs) {inputstream in = NULL; outputstream out = NULL; byte [] Buf = new byte [8*1024]; int n =-1; // record the actual byte length of each read try {In = new fileinputstream ("1.jpg "); // file 1.jpg: Out = new fileoutputstream ("1_copy.jpg"); While (n = in. read (BUF ))! =-1) {/** if it is written as out. write (BUF), the last write is always 8 K Bytes * even if the number of bytes for the last read is not set to 8 K */out. write (BUF, 0, n) ;}} catch (filenotfoundexception e) {system. out. println ("file not found. ");} catch (ioexception e) {system. out. println ("error happened. ");} finally {try {If (in! = NULL) {in. Close () ;}if (OUT! = NULL) {out. Flush (); Out. Close () ;}} catch (exception e ){}}}}
In addition, to buffer and read files, you can also use bufferedinputstream:
InputStream in = new BufferedInputStream( new FileInputStream("in.txt"), 8 * 1024);
Note: during initialization, the buffer size should be an integer multiple of 1024 to optimize the underlying operations.
References:
The class source code of nnu instructor Jiang is 'java _ course'