📌  相关文章
📜  Java中的 PrintStream write(byte[], int, int) 方法及示例

📅  最后修改于: 2022-05-13 01:54:41.569000             🧑  作者: Mango

Java中的 PrintStream write(byte[], int, int) 方法及示例

Java中PrintStream类的write(byte[], int, int)方法用于将指定byteacter数组的指定部分写入流上。这个 byteacter 数组被作为一个参数。要写入的字节符的起始索引和长度也作为参数。

句法:

参数:此方法接受三个强制参数:

  • byteArray ,它是要写入 Stream 的 byteacter 数组。
  • 起始索引,它是从其中获取 byteacter 部分的起始索引。
  • lengthOfCharArray是要写入流的字节码的长度。

返回值:此方法不返回任何值。

下面的方法说明了 write(byte[], int, int) 方法的工作:

方案一:

// Java program to demonstrate
// PrintStream write(byte[], int, int) method
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
  
            // Create a PrintStream instance
            PrintStream stream
                = new PrintStream(System.out);
  
            // Get the byteacter array
            // to be written in the stream
            byte[] byteArray = { 65, 66, 67 };
  
            // Get the starting index
            int startingIndex = 0;
  
            // Get the length of byte
            int lengthOfCharArray = 1;
  
            // Write the portion of the byteArray
            // to this stream using write() method
            // This will put the byteArray in the stream
            // till it is printed on the console
            stream.write(byteArray,
                         startingIndex,
                         lengthOfCharArray);
  
            stream.flush();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
A

方案二:

// Java program to demonstrate
// PrintStream write(byte[], int, int) method
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
  
            // Create a PrintStream instance
            PrintStream stream
                = new PrintStream(System.out);
  
            // Get the byteacter array
            // to be written in the stream
            byte[] byteArray = { 97, 98, 99 };
  
            // Get the starting index
            int startingIndex = 2;
  
            // Get the length of byte
            int lengthOfCharArray = 1;
  
            // Write the portion of the byteArray
            // to this stream using write() method
            // This will put the byteArray in the stream
            // till it is printed on the console
            stream.write(byteArray,
                         startingIndex,
                         lengthOfCharArray);
  
            stream.flush();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
c