java把一個檔案轉化為byte位元組

來源:互聯網
上載者:User

 

      最近做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擷取,這樣還可以加入斷點續傳的功能,排除了很多異常的問題! 這樣比較好!同時我也希望大家不要考慮用這種方式給用戶端傳送檔案!

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.