2016-03-18 43 views
0

我想從臨時文件中獲取字節數組。我知道我的連接有效,因爲我正在獲取地圖字符串的正確值。但我一直得到一個空字節數組。請幫忙!任何幫助是極大的讚賞!如何從下載的臨時文件獲取字節數組?

package packagename 
import android.content.Context; 
import android.os.AsyncTask; 
import android.util.Log; 
import com.microsoft.azure.storage.CloudStorageAccount; 
import com.microsoft.azure.storage.blob.CloudBlob; 
import com.microsoft.azure.storage.blob.CloudBlobClient; 
import com.microsoft.azure.storage.blob.CloudBlobContainer; 
import com.microsoft.azure.storage.blob.ListBlobItem; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.util.Hashtable; 
import java.util.Map; 

public class Getfilereference extends AsyncTask<Map<String,byte[]>,Void,Map<String,byte[]>> { 
    public Context mContext; 

    public Getfilereference(Context context) { 
     mContext = context; 
    } 

    @Override 
    protected Map<String, byte[]> doInBackground(Map<String, byte[]>... params) { 
     Map<String, byte[]> dictionary = new Hashtable<>(); 
     try { 
      final String storageConnectionString = 
        "myconnectionstring"; 
      final String azureblobstoragecontainername = "mycontainer"; 
      CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString); 
      CloudBlobClient blobClient = storageAccount.createCloudBlobClient(); 
      CloudBlobContainer container = blobClient.getContainerReference(azureblobstoragecontainername); 
      for (ListBlobItem blobItem : container.listBlobs()) { 
       if (blobItem instanceof CloudBlob) { 
        File file; 
        file = File.createTempFile("familyimages", null, mContext.getCacheDir()); 
        CloudBlob blob = (CloudBlob) blobItem; 
        blob.download(new FileOutputStream(file + "\\" + blob.getName())); 
        FileInputStream fis = new FileInputStream(file + "\\" + blob.getName()); 
        byte[] t = new byte[(file + "\\" + blob.getName()).length()]; 
        fis.read(t); 
        fis.close(); 
        dictionary.put(blob.getName(), t); 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return dictionary; 
    } 

    @Override 
    protected void onPostExecute(Map<String, byte[]> dictionary2) { 
     DirectoryOpenHelper dbhelper = new DirectoryOpenHelper(mContext); 
     for (Map.Entry<String, byte[]> entry : dictionary2.entrySet()) { 
      String key = entry.getKey(); 
      byte[] value = entry.getValue(); 
      dbhelper.openDB(); 
      dbhelper.insertfamilyimageinrow(value, Integer.valueOf(key)); 
      Log.i("Info",key); 
     } 
    } 
} 
+0

一個常見原因爲這個問題是,要讀出的流中的指針被定位在流的末尾。你可以通過將指針定位到流的起始位置來嘗試嗎? –

+0

請解釋。 – David

+0

究竟我該把讀者放在哪裏? – David

回答

0

我取代

byte[] t = new byte[(file + "\\" + blob.getName()).length()]; 
fis.read(t); fis.close(); dictionary.put(blob.getName(), t); 

RandomAccessFile f = new RandomAccessFile(file+"\\"+blob.getName(), "r"); 
byte[] b = new byte[(int)f.length()]; f.read(b); 
dictionary.put(blob.getName(), b);