Home> Java> javaTutorial> body text

When to use InputStream's readNBytes() method in Java 9?

王林
Release: 2023-08-30 09:21:02
forward
841 people have browsed it

在Java 9中何时使用InputStream的readNBytes()方法?

Since Java 9, thereadNBytes()method can be added to theInputStreamclass. This method reads the requested number of bytes from an input stream into the givenbyte array. This method blocks untillen bytesof input data have read, end of a stream is detected, or an exception is thrown. ThereadNBytes()method doesn't close an input stream. This method can be useful to avoidmemoryproblemswith large files.

Syntax

public int readNBytes(byte[] b, int off, int len) throws IOException
Copy after login

In the example below, we have created a file named "Technology.txt" in the source folder, It contains simple data:{ "JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"}.

Example

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(); } }
Copy after login

Output

"JAVA",
Copy after login

The above is the detailed content of When to use InputStream's readNBytes() method in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!