不使用任何循环读取字节

时间:2010-08-13 10:33:59

标签: java android

我有一个16mb的二进制文件,我想在不使用任何循环的情况下读取字节。就像我想要读取16个字节我可以将16传递给某个方法(如果有的话)并且它给了我想要的结果...现在我正在使用循环来读取字节但我的应用程序是如此巨大我害怕它不会变慢。请给我一些提示。

非常感谢。

4 个答案:

答案 0 :(得分:2)

我可以给你两个答案,但它们不实用。在现实生活中,你将使用循环来读取字节。

有效答案1

public byte[] readWithNoLoop(InputStream in, int size) {
   byte[] result = new byte[16777216];  // 16 MByte
   byte b = 0;

   if ((b = in.read()) >= 0) result[0] = b;
   if ((b = in.read()) >= 0) result[1] = b;
   if ((b = in.read()) >= 0) result[2] = b;

   // ...

   if ((b = in.read()) >= 0) result[16777215] = b;

   return b;
}

有效答案2

使用可以并行读取文件的大规模并行系统。您需要16777216个处理单元和一个支持文件存储系统,但您可以在O(1)中读取(理论上)。


如果在读取文件时遇到大量性能问题,请检查是否使用BufferedInputStream,从“普通”流中读取字节会导致性能下降。 (Example

如果它仍无效,请查看java.nio类。他们可以将文件映射到内存。 Grep example应该为您指明方向。

答案 1 :(得分:1)

答案 2 :(得分:0)

import java.io.*;

public class NoLoopReader {
  public static void main (String[] args) throws Exception {
    String fileName = args[0];
    InputStream is = new BufferedInputStream(new FileInputStream(fileName));
    File file = new File(fileName);
    int size = (int)file.length();

    byte[] buffer = new byte[size];
    is.read(buffer,0,size);
  }
}

答案 3 :(得分:0)

您可以检查磁盘上的文件大小,创建适当的缓冲区并使用此读取方法进行批量加载(因为您可以看到它调用本机readBytes)。当然我不知道readBytes中是否没有循环(最有可能存在,但这可能取决于JVM的实现)...... :)

在FileInputStream中

/**
 * Reads up to <code>b.length</code> bytes of data from this input
 * stream into an array of bytes. This method blocks until some input
 * is available.
 *
 * @param      b   the buffer into which the data is read.
 * @return     the total number of bytes read into the buffer, or
 *             <code>-1</code> if there is no more data because the end of
 *             the file has been reached.
 * @exception  IOException  if an I/O error occurs.
 */
public int read(byte b[]) throws IOException {

返回readBytes(b,0,b.length);     }

/**
 * Reads up to <code>len</code> bytes of data from this input stream
 * into an array of bytes. If <code>len</code> is not zero, the method
 * blocks until some input is available; otherwise, no
 * bytes are read and <code>0</code> is returned.
 *
 * @param      b     the buffer into which the data is read.
 * @param      off   the start offset in the destination array <code>b</code>
 * @param      len   the maximum number of bytes read.
 * @return     the total number of bytes read into the buffer, or
 *             <code>-1</code> if there is no more data because the end of
 *             the file has been reached.
 * @exception  NullPointerException If <code>b</code> is <code>null</code>.
 * @exception  IndexOutOfBoundsException If <code>off</code> is negative, 
 * <code>len</code> is negative, or <code>len</code> is greater than 
 * <code>b.length - off</code>
 * @exception  IOException  if an I/O error occurs.
 */
public int read(byte b[], int off, int len) throws IOException {

返回readBytes(b,off,len);     }