我有一个简单的java程序,它依赖于inputstream。我必须读取一个160 MB的ecg文件,该文件在普通的jvm上可以完美运行,但是当我在android中运行此代码时,它根本无法分配该160 MB并关闭我的应用程序。

下面是一段代码:

//      reads the ecg file into a stream and stores it in the InputArray
    public byte[] readStream() throws IOException{
        FileInputStream inputFile = new FileInputStream(getDataPath());
        setBytesToSkip(0);
        inputFile.skip(getBytesToSkip());
        setLengthOfInputFile(inputFile.available());
        byte[] InputArray = new byte[getLengthOfInputFile()];
        setInputArray(InputArray);
        inputFile.read(getInputArray());
        inputFile.close();
        return inputArray;

    }
//              writes the bytes of the inputArray into a buffer bb
            public ByteBuffer bufferStream(byte[] array){
        inputArray = array;
        setBufferOffset(0);
        setBufferByteReadLength(getLengthOfInputFile());

        ByteBuffer bb = ByteBuffer.allocateDirect(getBufferByteReadLength());
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.put(getInputArray(), getBufferOffset(), getBufferByteReadLength());
        return bb;
    }


我还尝试使用DirectBuffer超越普通堆,但仍然出现内存不足错误,例如:

dalvikvm-heap  PID:1715  Out of memory on a 167230992-byte allocation


有什么方法可以更有效地处理输入流的数据吗?或者我可以拿一些存储空间,例如一个SD卡作为“堆”?

最好的问候洛雷佐

最佳答案

通常,这是错误的方法。这些设备没有足够的内存供应用程序使用,如果需要,您需要记住您需要与手机上运行的所有其他应用程序共享该内存。但是,这是我立即注意到的几件事。

首先,您尝试两次分配160MB!

曾经在这里:

byte[] InputArray = new byte[getLengthOfInputFile()];


再次在这里:

ByteBuffer bb = ByteBuffer.allocateDirect(getBufferByteReadLength());


您可以尝试重新排列此代码,以免两次分配内存。

您还需要在清单中设置android:largeHeap="true"

关于android - 堆内存不足android,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19875960/

10-12 00:27
查看更多