最近做android的時候,同事說用一個URL擷取一張圖片太慢了,看能不能發位元組過來,我就測試了一下,把一個File的檔案轉化為一個byte[]數組位元組,下面是代碼:
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;/** * 把一個檔案轉化為byte[]資料,然後把位元組寫入一個新檔案裡面 * @author spring sky *<br> Email:vipa1888@163.com *<br> QQ:840950105 * */public class FileToByte {public static void main(String[] args) throws Exception {File file = new File("d:/a.png");byte[] b = getByte(file);/*** * 列印出位元組 * 每一行10個位元組 */for (int i = 0; i < b.length; i++) {System.out.print(b[i]);if(i%10==0&&i!=0) {System.out.print("\n");}}/** * 把得到的位元組寫到一個新的檔案裡面 */File newFile = new File("e:/我的新圖片.png");OutputStream os = new FileOutputStream(newFile);os.write(b); //把流一次性寫入一個檔案裡面 os.flush(); os.close();}/** * 把一個檔案轉化為位元組 * @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) //當檔案的長度超過了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;}//如果得到的位元組長度和file實際的長度不一致就可能出錯了if(offset<bytes.length){System.out.println("file length is error");return null;}is.close();}return bytes;}}
上面的getByte方法就可以得到了位元組,同時我把位元組轉化為檔案也是沒有問題的! 這種方式主要是用把檔案封裝在xml或者json中傳送,不過,我個人覺得伺服器端還是一樣給發送流,但是這種方式存在弊端,比如檔案過大,那麼位元組肯定會多了,這樣如果用戶端突然因為某些原因而串連不上了伺服器,將會導致檔案傳送的失敗!我不推薦這種方式,個人覺得還是使用url擷取,這樣還可以加入斷點續傳的功能,排除了很多異常的問題! 這樣比較好!同時我也希望大家不要考慮用這種方式給用戶端傳送檔案!