The day before yesterday the project team encountered file upload, the problem of increased memory. Deliberately read the relevant knowledge, but also have a certain understanding of this
try {fileinputstream fis=new fileinputstream (New File ("/home/saas/maven/maven.zip")); Bufferedinputstream bis=new bufferedinputstream (FIS); FileOutputStream fos=new FileOutputStream (New File ("/home/saas/bb.sh")); byte[] Buffer=new byte[1024*1024*1024];// This is a custom Java buffer int Len=0;while ((len=bis.read (buffer)) >0) {//fos.write (buffer, 0, Len);//The underlying//fos.flush () that seems to call the IO directly () ; System.out.println ("1024*1024*1024 Byte copied ");} Fis.close (); Fos.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}
First here a fileinputtream inside the Close method and the Flash () method does not call also will be the file, this file will also be copied successfully, and the data pair. The principle is this, because the FOS inside the local method called directly, the data is written to the file, so do not turn off the leaf can be successful, but do not shut down will cause memory can not be recycled, it is possible to cause a memory leak or something
Second, both Bufferedinputream and Bufferedoutputstream provide the cache, and you can see that there is a cache array buf[] default is 8092 bytes. The following is the source
/** * Writes the specified byte to this buffered output stream. * * @param b The byte to be written. * @exception IOException If an I/O error occurs. */public synchronized void write (int b) throws IOException { if (count >= buf.length) { flushbuffer (); } buf[count++] = (byte) b; }
Here first determine whether the buffer is now full, if not full, continue to write, if full, will be flushbuffer,flushbuffer actually will call the local method, the byte array of data written into the file, the following is the source
/** Flush the internal buffer */ private void Flushbuffer () throws IOException { if (Count > 0) { out.write (buf, 0, Count); Count = 0; } }
When you call Bufferoutputstream's write. If the incoming is FileInputStream, the bufferoutputsream inside will point to FileInputStream. Decorative patterns are used here.
In addition, you can see the source code, FileInputStream inside the flush is inherited outputstream, and outputstream in the flush is an empty method, nothing to do
Flush () and close () in File