> Java > java지도 시간 > 자바 ByteArrayOutputStream

자바 ByteArrayOutputStream

PHPz
풀어 주다: 2024-08-30 16:09:28
원래의
314명이 탐색했습니다.

In Java, ByteArrayOutputStream is a class that helps in writing common data into more than one file. Here, a byte array is used in order to write data that helps in writing data into multiple files. This stream holds a data copy and forwards the data into several streams. Based on the size of the data, the stream gets automatically larger. This class gets inherited from the package Java.io.ByteArrayOutputStream.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Declaration of Java ByteArrayOutputStream class

Below is the declaration:

public class ByteArrayOutputStream extends OutputStream
로그인 후 복사

Syntax

Following is the syntax:

ByteArrayOutputStream bobj = new ByteArrayOutputStream() ;
// A ByteArrayOutputStream with default size will get created
ByteArrayOutputStream bobj = new ByteArrayOutputStream(int n) ;
// A ByteArrayOutputStream with size n will get created
로그인 후 복사

How ByteArrayOutputStream classwork in Java?

Below are the steps to create a ByteArrayOutputStream in Java.

  • Import the package java.io.ByteArrayOutputStream.
  • Create an output stream as shown below.
ByteArrayOutputStream bobj = new ByteArrayOutputStream() ;
로그인 후 복사

or

ByteArrayOutputStream bobj = new ByteArrayOutputStream(int n) ;
로그인 후 복사
  • Perform different functionalities based on the requirement using the methods mentioned in the below sections.

Constructor

Java ByteArrayOutputStream has two constructors. They are:

ByteArrayOutputStream ( ): A ByteArrayOutputStream with default size will get created even though the size of the buffer gets increased if necessary.

ByteArrayOutputStream(int n):A ByteArrayOutputStream with size n bytes will get created.

Method

The following are the different methods that perform several functions.

  • int size() : The current buffer size will be returned on calling this method.
  • byte[] toByteArray(): A newly allocated array in bytes will get created.
  • String toString(): By decoding bytes with the help of a default character set in the platform, data will be converted into a string.
  • String toString(String cname): By decoding bytes with the help of character set cname in the platform, data will be converted into a string.
  • void write(int byt): Byte byt will be written to the ByteArrayOutputStream.
  • void write(byte[] byt , int offstart, int n): Byte byt of size n will be written to the ByteArrayOutputStream where the offset starts from offstart.
  • void writeTo(OutputStream o): The whole data of a byte array will be written to the ByteArrayOutputStreamO.
  • void reset(): Count field of the byte array will be reset to the value zero.
  • void close(): ByteArrayOutputStream will be closed on calling this method.

Examples of Java ByteArrayOutputStream

Now, let us see some of the sample examples.

Example #1

Java program to print the data from a byte array

Code:

import java.io.*;
//class
public class ByteExample {
//main method
public static void main(String args[])throws IOException {
//create an object for the bytearrayoutputstream
ByteArrayOutputStream bobj = new ByteArrayOutputStream(20);
while( bobj.size()!= 15 )
{
bobj.write("happy".getBytes());
}
byte byt [] = bobj.toByteArray();
System.out.println("The content gets printed as: ");
for(int i = 0; i<byt.length; i++) {
// print the characters
System.out.print((char)byt[i]  + "* * *");
}
System.out.println("   ");
}
}
로그인 후 복사

Output:

자바 ByteArrayOutputStream

In this program, a byteoutputstream is created, and each of the characters gets printed.

Example #2

Java program to print the data from a byte array and conversion of characters to upper case.

Code:

import java.io.*;
//class
public class ByteExample {
//main method
public static void main(String args[])throws IOException {
//create an object for the bytearrayoutputstream
ByteArrayOutputStream bobj = new ByteArrayOutputStream(20);
while( bobj.size()!= 15 )
{
bobj.write("happy".getBytes());
}
byte byt [] = bobj.toByteArray();
System.out.println("The content gets printed as: ");
for(int i = 0; i<byt.length; i++) {
// print the characters
System.out.print( ( char ) byt [ i ]  + "* * *");
}
System.out.println("   ");
int ch;
ByteArrayInputStream biobj = new ByteArrayInputStream(byt);
System.out.println("Conversion of each character to Upper case " );
for(int j = 0 ; j< 1; j++ ) {
while( ( ch = biobj.read( ) ) != - 1) {
//convert character to upper case
System.out.println(Character.toUpperCase( ( char ) ch ) );
}
biobj.reset( );
}
}
}
로그인 후 복사

Output:

자바 ByteArrayOutputStream

In this program also, a byteoutputstream is created, and each of the characters gets printed separated with *. Moreover, each character of the byte array gets converted to an upper case and printed.

Example #3

Java program to copy the content of a text file to another file.

Code:

import java.io.*;
//class
public class ByteExample {
//main method
public static void main(String args[])throws Exception
{
//create fileoutputstreams 1 and 2
FileOutputStream fobj1=new FileOutputStream("F:\\EduCBA\\May\\byte1.txt");
FileOutputStream fobj2=new FileOutputStream("F:\\EduCBA\\May\\byte2.txt");
//create bytearrayoutputstream
ByteArrayOutputStream bobj=new ByteArrayOutputStream();
//write the content
bobj.write(100);
//write to the text files
bobj.writeTo(fobj1);
bobj.writeTo(fobj2);
bobj.flush() ;
//
bobj.close() ;
System.out.println("Operation runs successfully...");
}
}
로그인 후 복사

Output:

In this program, two files byte1 and byte2, are created for copying the content from byte1 to byte2.

자바 ByteArrayOutputStream

On executing the code, the content of the byte1 files gets copied to byte2.

자바 ByteArrayOutputStream

Moreover, a line Operations runs successfully also gets printed in the console.

자바 ByteArrayOutputStream

Example #4

Program to implement bytearrayoutputstream using the methods toByteArray() and write(buff, offset, maximum length).

Code:

import java.io.*;
//class
public class ByteExample
{
//main method
public static void main(String[] args) throws IOException
{
//
ByteArrayOutputStream bobj = new ByteArrayOutputStream();
byte[] buff = { 'H', 'A' , 'P' , 'P' , 'Y' };
//write to the buffer
bobj.write(buff, 0, 5);
System.out.print(" write ( buffER , off set, max len) by toByteArray( ) usage : ");
// toByteArray() method usage
for ( byte byt: bobj.toByteArray( ) )
{
System.out.print("*" + byt );
}
}
}
로그인 후 복사

Output:

자바 ByteArrayOutputStream

In this program, the usage of different methods such as toArray( ) and write( buff, offset, maximum length) is explained.

결론

Java ByteArrayOutputStream은 바이트 배열의 도움으로 둘 이상의 파일에 공통 데이터를 쓰는 데 도움이 되는 클래스입니다. 여기서 스트림이 보유하는 데이터 사본은 여러 스트림으로 전달됩니다. 이 기사에서는 Java에서 ByteArrayOutputStream의 선언, 구문, 생성자, 메소드, 작업 및 실제 예제와 같은 여러 세부 사항을 자세히 설명합니다.

위 내용은 자바 ByteArrayOutputStream의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿