如何使用字节从BufferedInputStream创建一个字符串?

时间:2014-02-24 10:25:05

标签: java android string out-of-memory bufferedinputstream

我正在尝试读取文本文件并创建一个字符串。我使用以下代码:

 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。 在最后一行代码中,我得到以下异常:

 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 个答案:

答案 0 :(得分:2)

缓冲区太大。试试这个:

    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());