java - InputStream.available() 并从 oracle 中完整读取文件注释

标签 java android file-io inputstream bufferedreader

根据:

Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.

来自:

http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#available%28%29

和这个注释

In particular, code of the form

int n = in.available();
byte buf = new byte[n];
in.read(buf); 

is not guaranteed to read all of the remaining bytes from the given input stream.

http://docs.oracle.com/javase/8/docs/technotes/guides/io/troubleshooting.html

这是否意味着使用下面的函数导致无法完全读取文件?

/**
 * Reads a file from /raw/res/ and returns it as a byte array
 * @param res Resources instance for Mosembro
 * @param resourceId ID of resource (ex: R.raw.resource_name)
 * @return byte[] if successful, null otherwise
 */
public static byte[] readRawByteArray(Resources res, int resourceId)
{
    InputStream is = null;
    byte[] raw = new byte[] {};
    try {
        is = res.openRawResource(resourceId);
        raw = new byte[is.available()];
        is.read(raw);
    }
    catch (IOException e) {
        e.printStackTrace();
        raw = null;
    }
    finally {
        try {
            is.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    return raw;
}

最佳答案

available() 返回可以无阻塞地读取的字节数。该数字(可以为零)与文件的总长度之间没有必然的相关性。

关于java - InputStream.available() 并从 oracle 中完整读取文件注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25570213/

相关文章:

java - 安全地为 Multi-Tenancy 数据库创建新模式

java - 将字符串转换为 GregorianCalendar

java - 如何使用Sockets TCP在java和android之间正确传递对象?

java - 如何将 android 应用程序连接到非本地的 mysql 数据库?

java - 当我添加计时器时,图像将不再加载

java - 以编程方式发送 Whatsapp 消息到特定号码

c - 从 sscanf 读取的数字为 0

java - 为什么调用 OutputStream.flush() 时我的浏览器没有收到数据?

c++ - 将二维数组写入输出文件 - C++

java - 我的程序中出现未知 NullPointerException "Date"