Since Java 9, the readNBytes() method can be added to the InputStream class. This method reads the requested number of bytes from an input stream into the given byte array. This method blocks until len bytes of input data have read, end of a stream is detected, or an exception is thrown. The readNBytes() method doesn't close an input stream. This method can be useful to avoid memory problems with large files.
public int readNBytes(byte[] b, int off, int len) throws IOException
在下面的示例中,我们在源文件夹中创建了一个名为“Technology.txt”的文件,其中包含简单的数据:{ "JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"}。
示例
import java.io.*; import java.util.stream.*; import java.nio.*; import java.nio.file.*; public class InputStreamReadNByteMethodTest { InputStream inputStream = nputStreamReadNByteMethodTest.class.getResourceAsStream("Technology.txt"); public void testReadNBytes() throws Exception { final byte[] data = new byte[10]; inputStream.readNBytes(data, 0, 7); System.out.println(new String(data)); } public static void main(String args[]) throws Exception { InputStreamReadNByteMethodTest t = new InputStreamReadNByteMethodTest(); t.testReadNBytes(); } }
输出
"JAVA",
以上就是在Java 9中何时使用InputStream的readNBytes()方法?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。