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

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

王林
王林forward
2023-08-30 09:21:02957browse

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

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.

Syntax

<strong>public int readNBytes(byte[] b, int off, int len) throws IOException</strong>

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.<strong>getResourceAsStream</strong>("Technology.txt");

   public void testReadNBytes() throws Exception {
      final byte[] data = new byte[10];
      inputStream.<strong>readNBytes</strong>(data, 0, 7);
      System.out.println(new String(data));
   }
   public static void main(String args[]) throws Exception {
      InputStreamReadNByteMethodTest t = new InputStreamReadNByteMethodTest();
      t.testReadNBytes();  
   }
}

Output

<strong>"JAVA",</strong>

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Pattern classes in JavaNext article:Pattern classes in Java