[英]OutOfMemory Error while reading files to byte[]
I am trying to read video files in a byte[] and then encrypt them. 我正在尝试读取byte []中的视频文件,然后对其进行加密。 The files which are relatively large ie more than 30 mb are giving out of memory exception. 较大的文件(即大于30 mb)正在发出内存不足异常。 Here is the code I am using to read the file to byte[]: 这是我用来读取文件到byte []的代码:
FileInputStream fin=new FileInputStream(file);
byte[] fileContent = new byte[(int)file.length()];
fin.read(fileContent);
This is the error I am getting: 这是我得到的错误:
05-17 05:54:59.356: E/AndroidRuntime(4082): FATAL EXCEPTION: main
05-17 05:54:59.356: E/AndroidRuntime(4082): java.lang.OutOfMemoryError
05-17 05:54:59.356: E/AndroidRuntime(4082): at com.vencrypto.ExplorerActivity$3.onItemClick(ExplorerActivity.java:136)
05-17 05:54:59.356: E/AndroidRuntime(4082): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
05-17 05:54:59.356: E/AndroidRuntime(4082): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
05-17 05:54:59.356: E/AndroidRuntime(4082): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2788)
05-17 05:54:59.356: E/AndroidRuntime(4082): at android.widget.AbsListView$1.run(AbsListView.java:3463)
05-17 05:54:59.356: E/AndroidRuntime(4082): at android.os.Handler.handleCallback(Handler.java:730)
05-17 05:54:59.356: E/AndroidRuntime(4082): at android.os.Handler.dispatchMessage(Handler.java:92)
05-17 05:54:59.356: E/AndroidRuntime(4082): at android.os.Looper.loop(Looper.java:137)
05-17 05:54:59.356: E/AndroidRuntime(4082): at android.app.ActivityThread.main(ActivityThread.java:5103)
05-17 05:54:59.356: E/AndroidRuntime(4082): at java.lang.reflect.Method.invokeNative(Native Method)
05-17 05:54:59.356: E/AndroidRuntime(4082): at java.lang.reflect.Method.invoke(Method.java:525)
05-17 05:54:59.356: E/AndroidRuntime(4082): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-17 05:54:59.356: E/AndroidRuntime(4082): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-17 05:54:59.356: E/AndroidRuntime(4082): at dalvik.system.NativeStart.main(Native Method)
I know the files are too large but there must be a way right. 我知道文件太大,但是必须有正确的方法。
Instead of using a FileInputStream
directly, wrap that in a BufferedInputStream
, so that you don't allocate huge amounts of memory. 与其直接使用FileInputStream
,不如将其包装在BufferedInputStream
,这样就不会分配大量内存。 A buffered input stream reads the data in segments, so you can encrypt that piece, and, if you are writing it back to a file, use a BufferedWriter
to write that file in the same way. 缓冲的输入流按段读取数据,因此您可以对该段进行加密,并且,如果将其写回到文件中,请使用BufferedWriter
以相同的方式写入该文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.