Home  >  Article  >  Java  >  When to use InputStream's readAllBytes() method in Java 9?

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

WBOY
WBOYforward
2023-08-31 17:01:05507browse

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

Starting from Java 9, we can use the readAllBytes() method in the InputStream class to read all bytes into a byte array middle. This method reads all bytes from the InputStream object at once, and blocks until all remaining bytes have been read and the end of the stream is detected, or an exception is thrown.

>reallAllBytes() The method cannot automatically close the InputStream instance. When it reaches the end of the stream, further calls to this method can return an empty byte array. We can use this method in simple use cases where it is convenient to read all the bytes into a byte array rather than for reading an input stream with a large amount of data .

Syntax

<strong>public byte[] readAllBytes() throws IOException</strong>

In the example below, we have created a "Technology.txt" containing simple data in the "C:\Temp" folderFile: { "JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"}.

Example

import java.nio.*;
import java.nio.file.*;
import java.io.*;
import java.util.stream.*;
import java.nio.charset.StandardCharsets;

public class ReadAllBytesMethodTest {
   public static void main(String args[]) {
      try(<strong>InputStream </strong>stream = <strong>Files</strong>.newInputStream(<strong>Paths.get</strong>("C://Temp//Technology.txt"))) {
         <strong>// Convert stream to string</strong>
         String contents = new String(stream.<strong>readAllBytes()</strong>, <strong>StandardCharsets.UTF_8</strong>);

         <strong>// To print the string content</strong>
         System.out.println(contents);
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}

Output

<strong>"JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"</strong>

The above is the detailed content of When to use InputStream's readAllBytes() 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