The ByteArrayInputStream class is composed of two phases: Byte Array and one for Input Stream. Byte Array plays a pivotal role in holding the important data and the necessary bytes with respect to the input stream. Java ByteArrayInputStream class comprises of the internal buffer, which is responsible for reading the byte array as a stream. Byte array passes the data to be fed as an input stream. This data, when present in the buffer, gets increased. Traversal and retrieval of data become flexible and seamless using this class.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
public class ByteArrayInputStream extends InputStream
As part of the Java ByteArrayInputStream, the flow of execution is as follows:
A public class of ByteArrayInputStream is declared, which extends the interface as a medium to interact with the stream being put with the InputStream.
How Does ByteArrayInputStream Class Work in Java?
The working of ByteArrayInputStream is quite straight forward whose main principle is to convert the byte array into the input stream seamlessly. As an added advantage of this class, the buffer makes sure that the java.io.ByteArrayInput package consisting of the API lets you read the data from byte arrays as streams of the byte array, which is then turned into the input stream, which will be fed into the buffer. The ByteArrayInputstream is a subclass of the InputStream class. Therefore, the ByteArrayInputStream can be used as an InputStream. If the data is arranged and stored in an array as an input stream, this can be wrapped into a byte array and can turn into a stream easily. Once the ByteArrayInputStream object is ready, then a list of helper methods can be used for reading and doing operations on the stream.
Constructor of Java ByteArrayInputStream
The following constructors are used for supporting the ByteArrayInputStream class of java.
ByteArrayInputStream[byte a]
As part of the Java ByteArrayInputStream, this constructor works in a way that is used for accepting a prepared set of the byte array, especially as a parameter in the memory of the internal buffer present as part of the package and the class.
ByteArrayInputStream(byte [] a, int off, int len)
This constructor as part of the java ByteArrayInputStream class passes three arguments as a parameter from the stream, which takes into account the byte array, integer off and length of the defined integer, and the flow also maintains the order when fed as an input in the memory of the buffer which means that first the byte array a[], then two integer values where off Is the first byte to be read followed by the length of the number of bytes to be read.
Methods of Java ByteArrayInputStream
Below are the methods of Java ByteArrayInputStream:
- public int read()
- public int read(byte[] r, int off, int len)
- public int available()
- public void mark(int read)
- public long skip(long n)
- public boolean markSupported()
- public void reset()
- public void close()
1. public int read()
This method is part of the ByteArrayInputStream class is used for reading the next byte available in the already flowing input stream, which returns an int type of range 0-255. If there is no byte present in the buffer as the input stream, it has returned to an end of the stream, which returns -1 as value.
2. public int read(byte[] r, int off, int len)
This method reads the bytes upto the length of the number of bytes starting from the off from the input stream into an array and returns the total number of bytes until the last byte of -1 gets returned.
3. public int available()
As part of the ByteArrayInputStream class, this method is used for reading and acknowledging the total number of bytes that will be available from the Input stream to read.
4. public void mark(int read)
As part of the ByteArrayInputStream class, this method is used for marking and setting the current position of the input stream. Basically, it sets a reading limit for obtaining the maximum number of bytes that can be read before the marked limit set becomes invalid.
5. public long skip(long n)
As part of the ByteArrayInputStream class, this method is used for skipping the number of bytes in the input stream as an argument to the method.
6. public boolean markSupported()
This method is used for testing the input stream whether it supports the marked limit or functioning without its presence. It has one special feature that whenever this mark supported is used as a method; it returns a value always true.
7. public void reset()
This method is used to reset the position of the marker as it is provoked by the mark() method. The added advantage is to reposition and reset the marker for traversing.
8. public void close()
This method plays a crux to release all the resources once close. When It gets called, the input stream gets closed, and the stream gets associated with the garbage collector.
Examples to Implement of Java ByteArrayInputStream
Below are the examples of Java ByteArrayInputStream:
Example #1
This program is used to illustrate the read() method byte by byte in ByteArrayInputStream.
Code:
import java.io.*; public class Input_Buffer_Stream1 { public static void main(String[] args) throws Exception { byte guava = 0; byte pine = 0; byte kiwi = 0; byte orange = 0; byte[] buffr = {guava, pine, kiwi,orange}; ByteArrayInputStream fruits = new ByteArrayInputStream(buffr); int k = 0; while((k=fruits.read())!=-1) { System.out.println("These fruits are really tasty and relising to have & Its the time to have ad enjoy!"); } } }
Output:
Example #2
This program illustrates the available method of ByteArrayInputStream.
Code :
import java.io.ByteArrayInputStream; public class Input_Buffer_Stream2 { public static void main(String[] args) { byte[] buffr= {20,22}; ByteArrayInputStream bytes = new ByteArrayInputStream(buffr); int bytes_Available = bytes.available(); System.out.println("no of bytes available:" + bytes_Available); } }
Output:
Example #3
This program illustrates the mark method of the ByteArrayInputStream class.
Code:
import java.io.ByteArrayInputStream; public class Input_Buffer_Stream3 { public static void main(String[] args) { byte[] buffr= {20,22,19,10}; ByteArrayInputStream bytes_arr = new ByteArrayInputStream(buffr); bytes_arr.mark(0); System.out.println("These are the marked bytes of the stream:" + bytes_arr); } }
Output:
Example #4
This program illustrates the skip method of the ByteArrayInputStream class.
Code :
import java.io.ByteArrayInputStream; public class Input_Buffer_Stream4 { public static void main(String[] args) throws Exception { byte[] buffr= {20,22,18,10}; ByteArrayInputStream learning = null; learning = new ByteArrayInputStream(buffr); long num = learning.skip(1); System.out.println("Char : "+(char)learning.read()); } }
Output:
Example #5
This program illustrates the boolean mark supported method of the ByteArrayInputStream class.
Code :
import java.io.ByteArrayInputStream; public class Input_Buffer_Stream_5 { public static void main(String[] args) { byte[] buff = {15, 18, 20, 40, 52}; ByteArrayInputStream educba = null; educba = new ByteArrayInputStream(buff); boolean checker = educba.markSupported(); System.out.println("\n mark is supported for : "+ checker ); } }
Output:
Example #6
This program illustrates the presence of boolean mark, reset, and close method of the ByteArrayInputStream class.
Code:
import java.io.ByteArrayInputStream; import java.io.IOException; public class Input_Buffer_Stream_5 { public static void main(String[] args) { byte[] buff = {15, 18, 20, 40, 52}; ByteArrayInputStream educba = null; educba = new ByteArrayInputStream(buff); boolean checker = educba.markSupported(); System.out.println("\n mark is supported for : "+ checker ); if(educba.markSupported()) { educba.reset(); System.out.println("\n supports for the marking limit once reset"); System.out.println("Char : "+(char)educba.read()); } else { System.out.println("It is not supporting the positioning using reset method"); } System.out.println("educba.markSupported() supported reset() : "+checker); if(educba!=null) { try { educba.close(); } catch (IOException e) { e.printStackTrace(); } } } } <strong>Output:</strong>
Conclusion
Java ByteArrayInputStream is a class that has a lot of capability and versatility to play around with the arrays in the internal buffer, which is the beauty of the class. It does not require any external class or plugin to support its base methods which work with a lot of functionality. ByteArrayInputStream together forms a perfect combination to feed the input and output stream related data.
The above is the detailed content of Java ByteArrayInputStream. For more information, please follow other related articles on the PHP Chinese website!

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

Java'stopfeaturessignificantlyenhanceitsperformanceandscalability.1)Object-orientedprincipleslikepolymorphismenableflexibleandscalablecode.2)Garbagecollectionautomatesmemorymanagementbutcancauselatencyissues.3)TheJITcompilerboostsexecutionspeedafteri

The core components of the JVM include ClassLoader, RuntimeDataArea and ExecutionEngine. 1) ClassLoader is responsible for loading, linking and initializing classes and interfaces. 2) RuntimeDataArea contains MethodArea, Heap, Stack, PCRegister and NativeMethodStacks. 3) ExecutionEngine is composed of Interpreter, JITCompiler and GarbageCollector, responsible for the execution and optimization of bytecode.

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogrammingallowsmodelingreal-worldentities,exemplifiedbypolymorphism.2)Exceptionhandlingprovidesrobusterrormanagement.3)Lambdaexpressionssimplifyoperations,improvingcodereadability

TheJVMisacrucialcomponentthatrunsJavacodebytranslatingitintomachine-specificinstructions,impactingperformance,security,andportability.1)TheClassLoaderloads,links,andinitializesclasses.2)TheExecutionEngineexecutesbytecodeintomachineinstructions.3)Memo


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
