在android中读取大文件作为字节

时间:2016-07-15 11:18:26

标签: java android file-upload android-volley

我正在尝试在应用中实现上传功能。如果是小文件,它工作正常。但是当我尝试上传大文件时,它会抛出内存错误。

@Override
public byte[] getBody() {
   File file = new File(filepathnew);
   //  int size = (int) file.length();
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   try{
    BufferedInputStream reader = new BufferedInputStream(new FileInputStream (filepathnew));
    int read;
    byte[] buffer = new byte[32000];
    while ((read = reader.read(buffer)) >= 0) {
       baos.write(buffer, 0, read);
    }
    } catch (FileNotFoundException fnf){
       fnf.printStackTrace();
    } catch (IOException ioe){
       ioe.printStackTrace();
    }
       byte[] everything  = baos.toByteArray();
       return everything;
}

错误日志

E/AndroidRuntime: FATAL EXCEPTION: Thread-2667 Process: in.codme.cloudapp, PID: 15914
java.lang.OutOfMemoryError: Failed to allocate a 131008012 byte allocation with 16777216 free bytes and 50MB until OOM
at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
at in.codme.cloudapp.FileBrowserActivity$19.getBody(FileBrowserActivity.java:866)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:236)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:214)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:106)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:93)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)
07-15 16:47:02.869 15914-15916/in.codme.cloudapp W/art: Suspending all threads took: 49.184ms

0 个答案:

没有答案