How to Create a string from a BufferedInputStream using bytes?
本问题已经有最佳答案,请猛点这里访问。
我正在尝试读取文本文件并创建字符串。我使用以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 | String FILENAME ="file.txt"; File file = getApplicationContext().getFileStreamPath(FILENAME); int size = (int) file.length(); System.out.println("size:"+size); byte[] bytes = new byte[size]; BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file)); buf.read(bytes, 0, bytes.length); buf.close(); System.out.println("buf string:"+new String(bytes)); |
这种情况下的尺寸是5295164。在最后一行代码中,我得到以下异常:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | FATAL EXCEPTION: main java.lang.OutOfMemoryError at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:94) at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:145) at java.lang.StringBuilder.append(StringBuilder.java:216) at se.egretails.ssapp.MyActivity$4.onClick(MyActivity.java:461) at android.view.View.performClick(View.java:4084) at android.view.View$PerformClick.run(View.java:16966) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4812) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Method) |
我应该如何解决这个问题?事先谢谢。
缓冲区太大。试试这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | InputStream content = new FileInputStream(file); int numRead; final int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; ByteArrayOutputStream outString = new ByteArrayOutputStream(); try{ while ((numRead = content.read(buffer)) != -1) { outString.write(buffer, 0, numRead); } } finally { content.close(); } return new String(outString.toByteArray()); |