首页 > Java > java教程 > 在Java 9中何时使用InputStream的readNBytes()方法?

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

王林
发布: 2023-08-30 09:21:02
转载
952 人浏览过

在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>
登录后复制

在下面的示例中,我们在源文件夹中创建了一个名为“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.<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();  
   }
}
登录后复制

输出

<strong>"JAVA",</strong>
登录后复制

以上是在Java 9中何时使用InputStream的readNBytes()方法?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板