2015-01-05 1 views
8

sdcard에서 Base64로 파일을 변환하려고하는데 파일이 너무 크고 OutOfMemoryError가 나타납니다.안드로이드에서 Base64로 파일 (<100Mo)을 변환하십시오.

InputStream inputStream = null;//You can get an inputStream using any IO API 
inputStream = new FileInputStream(file.getAbsolutePath()); 
byte[] bytes; 
byte[] buffer = new byte[8192]; 
int bytesRead; 
ByteArrayOutputStream output = new ByteArrayOutputStream(); 
try { 
    while ((bytesRead = inputStream.read(buffer)) != -1) { 
     output.write(buffer, 0, bytesRead); 
    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
bytes = output.toByteArray(); 
attachedFile = Base64.encodeToString(bytes, Base64.DEFAULT); 

문자열 attachedFile을 제기하면서 OutOfMemoryError가 주위에 갈 수있는 방법이 있나요 : 여기

내 코드?

+0

사용이 코드가 도움이 https://stackoverflow.com/a/47572643/3505534 – R2R

답변

8

Base64 인코딩은 3 바이트를 취하여 4 바이트로 변환합니다. 그래서 만약 당신이 100 메가 비트 파일을 가지고 있다면 Base64에 133 메가 바이트가 될 것입니다. Java 문자열 (UTF-16)로 변환하면 크기가 두 배가됩니다. 물론 어떤 시점에서 변환 과정 중에 여러 복사본을 메모리에 보유 할 수 있습니다. 아무리 당신이 이것을 돌리더라도 거의 작동하지 않을 것입니다.

이 코드는 Base64OutputStream을 사용하는 코드가 약간 더 최적화되어 있으며 코드보다 메모리가 덜 필요하지만 숨을 멈추지는 않을 것입니다. 문자열에 대한 변환을 건너 뛰고 ByteArrayOutputStream 대신 임시 파일 스트림을 출력으로 사용하여 코드를 더 향상시키는 것이 좋습니다.

InputStream inputStream = null;//You can get an inputStream using any IO API 
inputStream = new FileInputStream(file.getAbsolutePath()); 
byte[] buffer = new byte[8192]; 
int bytesRead; 
ByteArrayOutputStream output = new ByteArrayOutputStream(); 
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT); 
try { 
    while ((bytesRead = inputStream.read(buffer)) != -1) { 
     output64.write(buffer, 0, bytesRead); 
    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
output64.close(); 

attachedFile = output.toString(); 
+1

될 것입니다 귀하의 답변을 주셔서 감사합니다! 나는 멀티 파트 (개조로)와 다른 볼 것입니다 ... – Labe

+0

좋은, 고마워 –

0
// Converting File to Base64.encode String type using Method 
    public String getStringFile(File f) { 
     InputStream inputStream = null; 
     String encodedFile= "", lastVal; 
     try { 
      inputStream = new FileInputStream(f.getAbsolutePath()); 

     byte[] buffer = new byte[10240];//specify the size to allow 
     int bytesRead; 
     ByteArrayOutputStream output = new ByteArrayOutputStream(); 
     Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT); 

      while ((bytesRead = inputStream.read(buffer)) != -1) { 
       output64.write(buffer, 0, bytesRead); 
      } 


     output64.close(); 


     encodedFile = output.toString(); 

     } 
     catch (FileNotFoundException e1) { 
       e1.printStackTrace(); 
      } 
      catch (IOException e) { 
       e.printStackTrace(); 
      } 
     lastVal = encodedFile; 
     return lastVal; 
    } 
관련 문제