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

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

WBOY
Release: 2023-08-31 17:01:05
forward
567 people have browsed it

在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>
Copy after login

In the example below, we have created a "Technology.txt" containing simple data in the "C:\Temp" folderFile: < strong>{ "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();
      }
   }
}
Copy after login

Output

<strong>"JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"</strong>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template