Recently, when I was working on Android, my colleague said it was too slow to get an image using a URL. I tested it if I could send bytes, convert a file into an array byte []. The following code is used:
Import Java. io. file; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. inputstream; import Java. io. outputstream;/*** convert a file into byte [] data, and then write the bytes into a new file * @ author spring sky * <br> Email: vipa1888@163.com * <br> QQ: 840950105 **/public class filetobyte {public static void main (string [] ARGs) throws exception {file = new file ("D: /a.png "); byte [] B = getbyte (File);/***** print the bytes * 10 bytes per row */For (INT I = 0; I <B. length; I ++) {system. out. print (B [I]); if (I % 10 = 0 & I! = 0) {system. out. print ("\ n") ;}}/*** write the obtained bytes to a new file */file newfile = new file ("E:/my new image .png "); outputstream OS = new fileoutputstream (newfile); OS. write (B); // write the stream to the OS in a file at a time. flush (); OS. close ();} /*** convert a file to a byte * @ Param file * @ return byte [] * @ throws exception */public static byte [] getbyte (File file) throws exception {byte [] bytes = NULL; If (file! = NULL) {inputstream is = new fileinputstream (File); int length = (INT) file. length (); If (length> integer. max_value) // when the file length exceeds the maximum value of int {system. out. println ("this file is Max"); return NULL;} bytes = new byte [length]; int offset = 0; int numread = 0; while (offset <bytes. length & (numread = is. read (bytes, offset, bytes. length-offset)> = 0) {Offset + = numread;} // an error may occur if (offset <bytes. length) {system. out. println ("file length is error"); return NULL;} is. close () ;}return bytes ;}}
The above getbyte method can get the byte, And I can convert the byte into a file! This method is mainly used to transfer a file package in XML or JSON. However, I personally think the server side is still sending a stream, but this method has drawbacks, such as the file is too large, so there will be more bytes, so if the client suddenly fails to connect to the server for some reason, it will lead to file transfer failure! I do not recommend this method. I personally think it is still possible to use the URL to obtain it. This can also be added to the resumable upload function, eliminating many exceptions! This is better! At the same time, I also hope that you will not consider using this method to send files to the client!