The following code can implement the ability to copy files in bytes, suitable for copying non-text types of files, in order to more clearly observe the operating rate, I joined the program timer, the code is as follows:
1 ImportJava.io.FileInputStream;2 ImportJava.io.FileOutputStream;3 Importjava.io.IOException;4 5 Public classYuan {6 /**7 * @paramargs8 */9 Public Static voidMain (string[] args) {Ten LongStartmili=System.currenttimemillis (); One Try { AFileInputStream FIS =NewFileInputStream ("A.mp3"); -FileOutputStream fos =NewFileOutputStream ("Temp.mp3"); - intRead =Fis.read (); (Read! =-1) {fos.write (read); + read = Fis.read (); + fis.close (); - fos.close (); +}Catch(IOException e) { A e.printstacktrace (); at } - LongEndmili=System.currenttimemillis (); -SYSTEM.OUT.PRINTLN ("Total time is:" + (Endmili-startmili) + "milliseconds"); - } -}
Operating effect:
However, this code is very inefficient when copying large files such as MP3, and I have improved the above code after class:
1 ImportJava.io.FileInputStream;2 ImportJava.io.FileOutputStream;3 Importjava.io.IOException;4 5 Public classCopys {6 /**7 * @paramargs8 */9 Public Static voidMain (string[] args) {Ten LongStartmili=system.currenttimemillis (); One Try { AFileInputStream FIS =NewFileInputStream ("A.mp3"); -FileOutputStream fos =NewFileOutputStream ("Temp.mp3"); - byte[] Bys =New byte[1024]; the intLen = 0;( len = Fis.read (bys))! =-1) {fos.write (bys, 0, Len); } + fis.close (); - fos.close (); +}Catch(IOException e) { A e.printstacktrace (); at } - LongEndmili=System.currenttimemillis (); -SYSTEM.OUT.PRINTLN ("Total time is:" + (Endmili-startmili) + "milliseconds"); - } -}
Note: The red code is a comparison of the code before and after improvement
Operating effect:
Summarize:
1. the byte stream copy file steps are as follows:
①. Constructing file bytes input/output stream
②. Create a byte array that specifies the size of each byte to be copied
③. Input stream reads bytes from source file, output stream writes bytes to file
2. the role of Fis.read (Bys) is to read bys.length bytes of data from the source file to the Bys array, returning the total number of bytes read in.
In this example, the length of the bys.length is specified as 1024000, when the last less than 1024000, for example, only 5000 bytes left, is returned 5000, at which time all bytes are read. The next read-in is returned-1 because the end of the file has been reached.
Fos.write (bys, 0, Len) means that a byte array is written to the file output stream from N bytes starting at offset 0.
3. close the input and output stream after the program finishes.
Java (iv)