Reading a binary input stream into a single byte array in Java

前端 未结 6 1921
陌清茗
陌清茗 2020-11-27 18:10

The documentation says that one should not use available() method to determine the size of an InputStream. How can I read the whole content of an <

6条回答
  •  半阙折子戏
    2020-11-27 18:53

    I believe buffer length needs to be specified, as memory is finite and you may run out of it

    Example:

    InputStream in = new FileInputStream(strFileName);
        long length = fileFileName.length();
    
        if (length > Integer.MAX_VALUE) {
            throw new IOException("File is too large!");
        }
    
        byte[] bytes = new byte[(int) length];
    
        int offset = 0;
        int numRead = 0;
    
        while (offset < bytes.length && (numRead = in.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
    
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + fileFileName.getName());
        }
    
        in.close();
    

提交回复
热议问题