Class BinaryData
BinaryData in its simplest form can be thought of as a container for content. Often this content is already in-memory as a String, byte array, or an Object that can be serialized into a String or byte[]. When the BinaryData is about to be sent to an Azure Service, this in-memory content is copied into the network request and sent to the service.
In more performance critical scenarios, where copying data into memory results in increased memory pressure, it is possible to create a BinaryData instance from a stream of data. From this, BinaryData can be connected directly to the outgoing network connection so that the stream is read directly to the network, without needing to first be read into memory on the system. Similarly, it is possible to read a stream of data from a BinaryData returned from an Azure Service without it first being read into memory. In many situations, these streaming operations can drastically reduce the memory pressure in applications, and so it is encouraged that all developers very carefully consider their ability to use the most appropriate API in BinaryData whenever they encounter an client library that makes use of BinaryData.
Refer to the documentation of each method in the BinaryData class to better understand its performance characteristics, and refer to the samples below to understand the common usage scenarios of this class.
BinaryData can be created from an InputStream, a Flux of ByteBuffer, a
String, an Object, a file, or a byte array.
A note on data mutability
BinaryData does not copy data on construction. BinaryData keeps a reference to the source content and is
accessed when a read request is made. So, any modifications to the underlying source before the content is read can
result in undefined behavior.
To create an instance of BinaryData, use the various static factory methods available. They all start with
'from' prefix, for example fromBytes(byte[]).
Create an instance from a byte array
final byte[] data = "Some Data".getBytes(StandardCharsets.UTF_8); BinaryData binaryData = BinaryData.fromBytes(data); System.out.println(new String(binaryData.toBytes(), StandardCharsets.UTF_8));
Create an instance from a String
final String data = "Some Data"; // Following will use default character set as StandardCharsets.UTF_8 BinaryData binaryData = BinaryData.fromString(data); System.out.println(binaryData.toString());
Create an instance from an InputStream
final ByteArrayInputStream inputStream = new ByteArrayInputStream("Some Data".getBytes(StandardCharsets.UTF_8));
BinaryData binaryData = BinaryData.fromStream(inputStream);
System.out.println(binaryData);
Create an instance from an Object
final Person data = new Person().setName("John");
// Provide your custom serializer or use Azure provided serializers.
// https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or
// https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson
BinaryData binaryData = BinaryData.fromObject(data);
System.out.println(binaryData);
Create an instance from Flux<ByteBuffer>
final byte[] data = "Some Data".getBytes(StandardCharsets.UTF_8);
final Flux<ByteBuffer> dataFlux = Flux.just(ByteBuffer.wrap(data));
Mono<BinaryData> binaryDataMono = BinaryData.fromFlux(dataFlux);
Disposable subscriber = binaryDataMono
.map(binaryData -> {
System.out.println(binaryData.toString());
return true;
})
.subscribe();
// So that your program wait for above subscribe to complete.
TimeUnit.SECONDS.sleep(5);
subscriber.dispose();
Create an instance from a file
BinaryData binaryData = BinaryData.fromFile(new File("path/to/file").toPath());
System.out.println(new String(binaryData.toBytes(), StandardCharsets.UTF_8));
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic BinaryDatafromByteBuffer(ByteBuffer data) Creates an instance ofBinaryDatafrom the givenByteBuffer.static BinaryDatafromBytes(byte[] data) Creates an instance ofBinaryDatafrom the given byte array.static BinaryDataCreates aBinaryDatathat uses the content of the file atPathas its data.static BinaryDataCreates aBinaryDatathat uses the content of the file atfileas its data.static BinaryDataCreates aBinaryDatathat uses the content of the file atfileas its data.static BinaryDataCreates aBinaryDatathat uses the content of the file atfileas its data.static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data, Long length) static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data, Long length, boolean bufferContent) static BinaryDatafromListByteBuffer(List<ByteBuffer> data) static BinaryDatafromObject(Object data) static BinaryDatafromObject(Object data, ObjectSerializer serializer) static Mono<BinaryData> fromObjectAsync(Object data) static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) static BinaryDatafromStream(InputStream inputStream) Creates an instance ofBinaryDatafrom the givenInputStream.static BinaryDatafromStream(InputStream inputStream, Long length) Creates an instance ofBinaryDatafrom the givenInputStream.static Mono<BinaryData> fromStreamAsync(InputStream inputStream) Creates an instance ofBinaryDatafrom the givenInputStream.static Mono<BinaryData> fromStreamAsync(InputStream inputStream, Long length) Creates an instance ofBinaryDatafrom the givenInputStream.static BinaryDatafromString(String data) Creates an instance ofBinaryDatafrom the givenString.Returns the length of the content, if it is known.booleanReturns a flag indicating whether the content can be repeatedly consumed using all accessors includingtoStream()andtoFluxByteBuffer()Returns a read-onlyByteBufferrepresentation of thisBinaryData.byte[]toBytes()Returns a byte array representation of thisBinaryData.Returns the content of thisBinaryDatainstance as a flux ofByteBuffers.<T> TtoObject(TypeReference<T> typeReference) Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the defaultJsonSerializer.<T> TtoObject(TypeReference<T> typeReference, ObjectSerializer serializer) Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the passedObjectSerializer.<T> TReturns anObjectrepresentation of thisBinaryDataby deserializing its data using the defaultJsonSerializer.<T> TtoObject(Class<T> clazz, ObjectSerializer serializer) Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the passedObjectSerializer.<T> Mono<T> toObjectAsync(TypeReference<T> typeReference) Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the defaultJsonSerializer.<T> Mono<T> toObjectAsync(TypeReference<T> typeReference, ObjectSerializer serializer) Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the passedObjectSerializer.<T> Mono<T> toObjectAsync(Class<T> clazz) Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the defaultJsonSerializer.<T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the passedObjectSerializer.Converts theBinaryDatainto aBinaryDatathat is replayable, i.e. content can be consumed repeatedly using all accessors includingtoStream()andtoFluxByteBuffer()Converts theBinaryDatainto aBinaryDatathat is replayable, i.e. content can be consumed repeatedly using all accessors includingtoStream()andtoFluxByteBuffer()toStream()Returns anInputStreamrepresentation of thisBinaryData.toString()Returns aStringrepresentation of thisBinaryDataby converting its data using the UTF-8 character set.voidwriteTo(com.azure.json.JsonWriter jsonWriter) Writes the contents of thisBinaryDatato the givenJsonWriter.voidwriteTo(OutputStream outputStream) Writes the contents of thisBinaryDatato the givenOutputStream.writeTo(AsynchronousByteChannel channel) Writes the contents of thisBinaryDatato the givenAsynchronousByteChannel.voidwriteTo(WritableByteChannel channel) Writes the contents of thisBinaryDatato the givenWritableByteChannel.
-
Method Details
-
fromStream
Creates an instance ofBinaryDatafrom the givenInputStream. Depending on the type of inputStream, the BinaryData instance created may or may not allow reading the content more than once. The stream content is not cached if the stream is not read into a format that requires the content to be fully read into memory.NOTE: The
InputStreamis not closed by this function.Create an instance from an InputStream
final ByteArrayInputStream inputStream = new ByteArrayInputStream("Some Data".getBytes(StandardCharsets.UTF_8)); BinaryData binaryData = BinaryData.fromStream(inputStream); System.out.println(binaryData);- Parameters:
inputStream- TheInputStreamthatBinaryDatawill represent.- Returns:
- A
BinaryDatarepresenting theInputStream. - Throws:
UncheckedIOException- If any error happens while reading theInputStream.NullPointerException- IfinputStreamis null.
-
fromStream
Creates an instance ofBinaryDatafrom the givenInputStream. Depending on the type of inputStream, the BinaryData instance created may or may not allow reading the content more than once. The stream content is not cached if the stream is not read into a format that requires the content to be fully read into memory.NOTE: The
InputStreamis not closed by this function.Create an instance from an InputStream
byte[] bytes = "Some Data".getBytes(StandardCharsets.UTF_8); final ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); BinaryData binaryData = BinaryData.fromStream(inputStream, (long) bytes.length); System.out.println(binaryData);
- Parameters:
inputStream- TheInputStreamthatBinaryDatawill represent.length- The length ofdatain bytes.- Returns:
- A
BinaryDatarepresenting theInputStream. - Throws:
UncheckedIOException- If any error happens while reading theInputStream.NullPointerException- IfinputStreamis null.
-
fromStreamAsync
Creates an instance ofBinaryDatafrom the givenInputStream. NOTE: TheInputStreamis not closed by this function.Create an instance from an InputStream
final ByteArrayInputStream inputStream = new ByteArrayInputStream("Some Data".getBytes(StandardCharsets.UTF_8)); Mono<BinaryData> binaryDataMono = BinaryData.fromStreamAsync(inputStream); Disposable subscriber = binaryDataMono .map(binaryData -> { System.out.println(binaryData.toString()); return true; }) .subscribe(); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();- Parameters:
inputStream- TheInputStreamthatBinaryDatawill represent.- Returns:
- A
MonoofBinaryDatarepresenting theInputStream. - Throws:
UncheckedIOException- If any error happens while reading theInputStream.NullPointerException- IfinputStreamis null.
-
fromStreamAsync
Creates an instance ofBinaryDatafrom the givenInputStream. NOTE: TheInputStreamis not closed by this function.Create an instance from an InputStream
byte[] bytes = "Some Data".getBytes(StandardCharsets.UTF_8); final ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); Mono<BinaryData> binaryDataMono = BinaryData.fromStreamAsync(inputStream, (long) bytes.length); Disposable subscriber = binaryDataMono .map(binaryData -> { System.out.println(binaryData.toString()); return true; }) .subscribe(); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();- Parameters:
inputStream- TheInputStreamthatBinaryDatawill represent.length- The length ofdatain bytes.- Returns:
- A
MonoofBinaryDatarepresenting theInputStream. - Throws:
UncheckedIOException- If any error happens while reading theInputStream.NullPointerException- IfinputStreamis null.
-
fromFlux
Creates an instance ofBinaryDatafrom the givenFluxofByteBuffer.Create an instance from a Flux of ByteBuffer
This method aggregates data into single byte array.
final byte[] data = "Some Data".getBytes(StandardCharsets.UTF_8); final Flux<ByteBuffer> dataFlux = Flux.just(ByteBuffer.wrap(data)); Mono<BinaryData> binaryDataMono = BinaryData.fromFlux(dataFlux); Disposable subscriber = binaryDataMono .map(binaryData -> { System.out.println(binaryData.toString()); return true; }) .subscribe(); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();- Parameters:
data- TheFluxofByteBufferthatBinaryDatawill represent.- Returns:
- A
MonoofBinaryDatarepresenting theFluxofByteBuffer. - Throws:
NullPointerException- Ifdatais null.
-
fromFlux
Creates an instance ofBinaryDatafrom the givenFluxofByteBuffer.Create an instance from a Flux of ByteBuffer
This method aggregates data into single byte array.
final byte[] data = "Some Data".getBytes(StandardCharsets.UTF_8); final long length = data.length; final Flux<ByteBuffer> dataFlux = Flux.just(ByteBuffer.wrap(data)); Mono<BinaryData> binaryDataMono = BinaryData.fromFlux(dataFlux, length); Disposable subscriber = binaryDataMono .map(binaryData -> { System.out.println(binaryData.toString()); return true; }) .subscribe(); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();- Parameters:
data- TheFluxofByteBufferthatBinaryDatawill represent.length- The length ofdatain bytes.- Returns:
- A
MonoofBinaryDatarepresenting theFluxofByteBuffer. - Throws:
IllegalArgumentException- if the length is less than zero.NullPointerException- ifdatais null.
-
fromFlux
Creates an instance ofBinaryDatafrom the givenFluxofByteBuffer.If
bufferContentis true andlengthis null the length of the returnedBinaryDatawill be based on the length calculated by buffering. Iflengthis non-null it will always be used as theBinaryDatalength even if buffering determines a different length.Create an instance from a Flux of ByteBuffer
final byte[] data = "Some Data".getBytes(StandardCharsets.UTF_8); final long length = data.length; final boolean shouldAggregateData = false; final Flux<ByteBuffer> dataFlux = Flux.just(ByteBuffer.wrap(data)); Mono<BinaryData> binaryDataMono = BinaryData.fromFlux(dataFlux, length, shouldAggregateData); Disposable subscriber = binaryDataMono .map(binaryData -> { System.out.println(binaryData.toString()); return true; }) .subscribe(); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();- Parameters:
data- TheFluxofByteBufferthatBinaryDatawill represent.length- The length ofdatain bytes.bufferContent- A flag indicating whetherFluxshould be buffered eagerly or consumption deferred.- Returns:
- A
MonoofBinaryDatarepresenting theFluxofByteBuffer. - Throws:
IllegalArgumentException- if the length is less than zero.NullPointerException- ifdatais null.
-
fromString
Creates an instance ofBinaryDatafrom the givenString.The
Stringis converted into bytes usingString.getBytes(Charset)passingStandardCharsets.UTF_8.Create an instance from a String
final String data = "Some Data"; // Following will use default character set as StandardCharsets.UTF_8 BinaryData binaryData = BinaryData.fromString(data); System.out.println(binaryData.toString());
- Parameters:
data- TheStringthatBinaryDatawill represent.- Returns:
- A
BinaryDatarepresenting theString. - Throws:
NullPointerException- Ifdatais null.
-
fromBytes
Creates an instance ofBinaryDatafrom the given byte array.If the byte array is zero length an empty
BinaryDatawill be returned. Note that the input byte array is used as a reference by this instance ofBinaryDataand any changes to the byte array outside of this instance will result in the contents of this BinaryData instance being updated as well. To safely update the byte array without impacting the BinaryData instance, perform an array copy first.Create an instance from a byte array
final byte[] data = "Some Data".getBytes(StandardCharsets.UTF_8); BinaryData binaryData = BinaryData.fromBytes(data); System.out.println(new String(binaryData.toBytes(), StandardCharsets.UTF_8));
- Parameters:
data- The byte array thatBinaryDatawill represent.- Returns:
- A
BinaryDatarepresenting the byte array. - Throws:
NullPointerException- Ifdatais null.
-
fromByteBuffer
Creates an instance ofBinaryDatafrom the givenByteBuffer.If the
ByteBufferis zero length an emptyBinaryDatawill be returned. Note that the inputByteBufferis used as a reference by this instance ofBinaryDataand any changes to theByteBufferoutside of this instance will result in the contents of this BinaryData instance being updated as well. To safely update theByteBufferwithout impacting the BinaryData instance, perform an array copy first.Create an instance from a ByteBuffer
final ByteBuffer data = ByteBuffer.wrap("Some Data".getBytes(StandardCharsets.UTF_8)); BinaryData binaryData = BinaryData.fromByteBuffer(data); System.out.println(binaryData);- Parameters:
data- TheByteBufferthatBinaryDatawill represent.- Returns:
- A
BinaryDatarepresenting theByteBuffer. - Throws:
NullPointerException- Ifdatais null.
-
fromListByteBuffer
Creates an instance ofBinaryDatafrom the givenListofByteBuffer.The input
ByteBufferinstances are used as a reference by this instance ofBinaryDataand any changes to aByteBufferoutside of this instance will result in the contents of this BinaryData instance being updated as well. To safely update the byte array without impacting the BinaryData instance, perform an array copy first.Create an instance from a List<ByteBuffer>
final List<ByteBuffer> data = Stream.of("Some ", "data") .map(s -> ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); BinaryData binaryData = BinaryData.fromListByteBuffer(data); System.out.println(binaryData);- Parameters:
data- TheListofByteBufferthatBinaryDatawill represent.- Returns:
- A
BinaryDatarepresenting theListofByteBuffer.
-
fromObject
Creates an instance ofBinaryDataby serializing theObjectusing the defaultJsonSerializer.Note: This method first looks for a
JsonSerializerProviderimplementation on the classpath. If no implementation is found, a default Jackson-based implementation will be used to serialize the object.Creating an instance from an Object
final Person data = new Person().setName("John"); // Provide your custom serializer or use Azure provided serializers. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson BinaryData binaryData = BinaryData.fromObject(data); System.out.println(binaryData);- Parameters:
data- The object that will be JSON serialized thatBinaryDatawill represent.- Returns:
- A
BinaryDatarepresenting the JSON serialized object. - Throws:
NullPointerException- Ifdatais null.- See Also:
-
fromObjectAsync
Creates an instance ofBinaryDataby serializing theObjectusing the defaultJsonSerializer.Note: This method first looks for a
JsonSerializerProviderimplementation on the classpath. If no implementation is found, a default Jackson-based implementation will be used to serialize the object.Creating an instance from an Object
final Person data = new Person().setName("John"); // Provide your custom serializer or use Azure provided serializers. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson Disposable subscriber = BinaryData.fromObjectAsync(data) .subscribe(binaryData -> System.out.println(binaryData.toString())); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();- Parameters:
data- The object that will be JSON serialized thatBinaryDatawill represent.- Returns:
- A
MonoofBinaryDatarepresenting the JSON serialized object. - See Also:
-
fromObject
Creates an instance ofBinaryDataby serializing theObjectusing the passedObjectSerializer.The passed
ObjectSerializercan either be one of the implementations offered by the Azure SDKs or your own implementation.Azure SDK implementations
Create an instance from an Object
final Person data = new Person().setName("John"); // Provide your custom serializer or use Azure provided serializers. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer BinaryData binaryData = BinaryData.fromObject(data, serializer); System.out.println(binaryData.toString());- Parameters:
data- The object that will be serialized thatBinaryDatawill represent. Theserializerdetermines hownulldata is serialized.serializer- TheObjectSerializerused to serialize object.- Returns:
- A
BinaryDatarepresenting the serialized object. - Throws:
NullPointerException- Ifserializeris null.- See Also:
-
fromObjectAsync
Creates an instance ofBinaryDataby serializing theObjectusing the passedObjectSerializer.The passed
ObjectSerializercan either be one of the implementations offered by the Azure SDKs or your own implementation.Azure SDK implementations
Create an instance from an Object
final Person data = new Person().setName("John"); // Provide your custom serializer or use Azure provided serializers. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer Disposable subscriber = BinaryData.fromObjectAsync(data, serializer) .subscribe(binaryData -> System.out.println(binaryData.toString())); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();- Parameters:
data- The object that will be serialized thatBinaryDatawill represent. Theserializerdetermines hownulldata is serialized.serializer- TheObjectSerializerused to serialize object.- Returns:
- A
MonoofBinaryDatarepresenting the serialized object. - Throws:
NullPointerException- Ifserializeris null.- See Also:
-
fromFile
Creates aBinaryDatathat uses the content of the file atPathas its data. This method checks for the existence of the file at the time of creating an instance ofBinaryData. The file, however, is not read until there is an attempt to read the contents of the returned BinaryData instance.Create an instance from a file
The
BinaryDatareturned from this method uses 8KB chunk size when reading file content.BinaryData binaryData = BinaryData.fromFile(new File("path/to/file").toPath()); System.out.println(new String(binaryData.toBytes(), StandardCharsets.UTF_8));- Parameters:
file- ThePaththat will be theBinaryDatadata.- Returns:
- A new
BinaryData. - Throws:
NullPointerException- Iffileis null.
-
fromFile
Creates aBinaryDatathat uses the content of the file atfileas its data. This method checks for the existence of the file at the time of creating an instance ofBinaryData. The file, however, is not read until there is an attempt to read the contents of the returned BinaryData instance.Create an instance from a file
BinaryData binaryData = BinaryData.fromFile(new File("path/to/file").toPath(), 8092); System.out.println(new String(binaryData.toBytes(), StandardCharsets.UTF_8));- Parameters:
file- ThePaththat will be theBinaryDatadata.chunkSize- The requested size for each read of the path.- Returns:
- A new
BinaryData. - Throws:
NullPointerException- Iffileis null.IllegalArgumentException- Ifoffsetorlengthare negative oroffsetpluslengthis greater than the file size orchunkSizeis less than or equal to 0.UncheckedIOException- if the file does not exist.
-
fromFile
Creates aBinaryDatathat uses the content of the file atfileas its data. This method checks for the existence of the file at the time of creating an instance ofBinaryData. The file, however, is not read until there is an attempt to read the contents of the returned BinaryData instance.Create an instance from a file
The
BinaryDatareturned from this method uses 8KB chunk size when reading file content.long position = 1024; long length = 100 * 1048; BinaryData binaryData = BinaryData.fromFile( new File("path/to/file").toPath(), position, length); System.out.println(new String(binaryData.toBytes(), StandardCharsets.UTF_8));- Parameters:
file- ThePaththat will be theBinaryDatadata.position- Position, or offset, within the path where reading begins.length- Maximum number of bytes to be read from the path.- Returns:
- A new
BinaryData. - Throws:
NullPointerException- Iffileis null.IllegalArgumentException- Ifoffsetorlengthare negative oroffsetpluslengthis greater than the file size orchunkSizeis less than or equal to 0.UncheckedIOException- if the file does not exist.
-
fromFile
Creates aBinaryDatathat uses the content of the file atfileas its data. This method checks for the existence of the file at the time of creating an instance ofBinaryData. The file, however, is not read until there is an attempt to read the contents of the returned BinaryData instance.Create an instance from a file
long position = 1024; long length = 100 * 1048; int chunkSize = 8092; BinaryData binaryData = BinaryData.fromFile( new File("path/to/file").toPath(), position, length, chunkSize); System.out.println(new String(binaryData.toBytes(), StandardCharsets.UTF_8));- Parameters:
file- ThePaththat will be theBinaryDatadata.position- Position, or offset, within the path where reading begins.length- Maximum number of bytes to be read from the path.chunkSize- The requested size for each read of the path.- Returns:
- A new
BinaryData. - Throws:
NullPointerException- Iffileis null.IllegalArgumentException- Ifoffsetorlengthare negative oroffsetpluslengthis greater than the file size orchunkSizeis less than or equal to 0.UncheckedIOException- if the file does not exist.
-
toBytes
public byte[] toBytes()Returns a byte array representation of thisBinaryData.This method returns a reference to the underlying byte array. Modifying the contents of the returned byte array may change the content of this BinaryData instance. If the content source of this BinaryData instance is a file, an
InputStream, or aFlux<ByteBuffer>the source is not modified. To safely update the byte array, it is recommended to make a copy of the contents first.If the
BinaryDatais larger than the maximum size allowed for abyte[]this will throw anIllegalStateException.- Returns:
- A byte array representing this
BinaryData. - Throws:
IllegalStateException- If theBinaryDatais larger than the maximum size allowed for abyte[].
-
toString
Returns aStringrepresentation of thisBinaryDataby converting its data using the UTF-8 character set. A new instance of String is created each time this method is called.If the
BinaryDatais larger than the maximum size allowed for aStringthis will throw anIllegalStateException.- Overrides:
toStringin classObject- Returns:
- A
Stringrepresenting thisBinaryData. - Throws:
IllegalStateException- If theBinaryDatais larger than the maximum size allowed for aString.
-
toObject
Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the defaultJsonSerializer. Each time this method is called, the content is deserialized and a new instance of typeTis returned. So, calling this method repeatedly to convert the underlying data source into the same type is not recommended.The type, represented by
Class, should be a non-generic class, for generic classes usetoObject(TypeReference).Note: This method first looks for a
JsonSerializerProviderimplementation on the classpath. If no implementation is found, a default Jackson-based implementation will be used to deserialize the object.Get a non-generic Object from the BinaryData
final Person data = new Person().setName("John"); // Ensure your classpath have the Serializer to serialize the object which implement implement // com.azure.core.util.serializer.JsonSerializer interface. // Or use Azure provided libraries for this. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson BinaryData binaryData = BinaryData.fromObject(data); Person person = binaryData.toObject(Person.class); System.out.println(person.getName());- Type Parameters:
T- Type of the deserialized Object.- Parameters:
clazz- TheClassrepresenting the Object's type.- Returns:
- An
Objectrepresenting the JSON deserializedBinaryData. - Throws:
NullPointerException- Ifclazzis null.- See Also:
-
toObject
Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the defaultJsonSerializer. Each time this method is called, the content is deserialized and a new instance of typeTis returned. So, calling this method repeatedly to convert the underlying data source into the same type is not recommended.The type, represented by
TypeReference, can either be a generic or non-generic type. If the type is generic create a sub-type ofTypeReference, if the type is non-generic useTypeReference.createInstance(Class).Note: This method first looks for a
JsonSerializerProviderimplementation on the classpath. If no implementation is found, a default Jackson-based implementation will be used to deserialize the object.Get a non-generic Object from the BinaryData
final Person data = new Person().setName("John"); // Ensure your classpath have the Serializer to serialize the object which implement implement // com.azure.core.util.serializer.JsonSerializer interface. // Or use Azure provided libraries for this. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson BinaryData binaryData = BinaryData.fromObject(data); Person person = binaryData.toObject(TypeReference.createInstance(Person.class)); System.out.println(person.getName());Get a generic Object from the BinaryData
final Person person1 = new Person().setName("John"); final Person person2 = new Person().setName("Jack"); List<Person> personList = new ArrayList<>(); personList.add(person1); personList.add(person2); // Ensure your classpath have the Serializer to serialize the object which implement implement // com.azure.core.util.serializer.JsonSerializer interface. // Or use Azure provided libraries for this. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson BinaryData binaryData = BinaryData.fromObject(personList); List<Person> persons = binaryData.toObject(new TypeReference<List<Person>>() { }); persons.forEach(person -> System.out.println(person.getName()));- Type Parameters:
T- Type of the deserialized Object.- Parameters:
typeReference- TheTypeReferencerepresenting the Object's type.- Returns:
- An
Objectrepresenting the JSON deserializedBinaryData. - Throws:
NullPointerException- IftypeReferenceis null.- See Also:
-
toObject
Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the passedObjectSerializer. Each time this method is called, the content is deserialized and a new instance of typeTis returned. So, calling this method repeatedly to convert the underlying data source into the same type is not recommended.The type, represented by
Class, should be a non-generic class, for generic classes usetoObject(TypeReference, ObjectSerializer).The passed
ObjectSerializercan either be one of the implementations offered by the Azure SDKs or your own implementation.Azure SDK implementations
Get a non-generic Object from the BinaryData
final Person data = new Person().setName("John"); // Provide your custom serializer or use Azure provided serializers. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer BinaryData binaryData = BinaryData.fromObject(data, serializer); Person person = binaryData.toObject(Person.class, serializer); System.out.println("Name : " + person.getName());- Type Parameters:
T- Type of the deserialized Object.- Parameters:
clazz- TheClassrepresenting the Object's type.serializer- TheObjectSerializerused to deserialize object.- Returns:
- An
Objectrepresenting the deserializedBinaryData. - Throws:
NullPointerException- Ifclazzorserializeris null.- See Also:
-
toObject
Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the passedObjectSerializer. Each time this method is called, the content is deserialized and a new instance of typeTis returned. So, calling this method repeatedly to convert the underlying data source into the same type is not recommended.The type, represented by
TypeReference, can either be a generic or non-generic type. If the type is generic create a sub-type ofTypeReference, if the type is non-generic useTypeReference.createInstance(Class).The passed
ObjectSerializercan either be one of the implementations offered by the Azure SDKs or your own implementation.Azure SDK implementations
Get a non-generic Object from the BinaryData
final Person data = new Person().setName("John"); // Provide your custom serializer or use Azure provided serializers. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer BinaryData binaryData = BinaryData.fromObject(data, serializer); Person person = binaryData.toObject(TypeReference.createInstance(Person.class), serializer); System.out.println("Name : " + person.getName());Get a generic Object from the BinaryData
final Person person1 = new Person().setName("John"); final Person person2 = new Person().setName("Jack"); List<Person> personList = new ArrayList<>(); personList.add(person1); personList.add(person2); final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer BinaryData binaryData = BinaryData.fromObject(personList, serializer); // Retains the type of the list when deserializing List<Person> persons = binaryData.toObject(new TypeReference<List<Person>>() { }, serializer); persons.forEach(person -> System.out.println("Name : " + person.getName()));- Type Parameters:
T- Type of the deserialized Object.- Parameters:
typeReference- TheTypeReferencerepresenting the Object's type.serializer- TheObjectSerializerused to deserialize object.- Returns:
- An
Objectrepresenting the deserializedBinaryData. - Throws:
NullPointerException- IftypeReferenceorserializeris null.- See Also:
-
toObjectAsync
Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the defaultJsonSerializer. Each time this method is called, the content is deserialized and a new instance of typeTis returned. So, calling this method repeatedly to convert the underlying data source into the same type is not recommended.The type, represented by
Class, should be a non-generic class, for generic classes usetoObject(TypeReference).Note: This method first looks for a
JsonSerializerProviderimplementation on the classpath. If no implementation is found, a default Jackson-based implementation will be used to deserialize the object.Get a non-generic Object from the BinaryData
final Person data = new Person().setName("John"); // Ensure your classpath have the Serializer to serialize the object which implement implement // com.azure.core.util.serializer.JsonSerializer interface. // Or use Azure provided libraries for this. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson BinaryData binaryData = BinaryData.fromObject(data); Disposable subscriber = binaryData.toObjectAsync(Person.class) .subscribe(person -> System.out.println(person.getName())); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();- Type Parameters:
T- Type of the deserialized Object.- Parameters:
clazz- TheClassrepresenting the Object's type.- Returns:
- A
MonoofObjectrepresenting the JSON deserializedBinaryData. - Throws:
NullPointerException- Ifclazzis null.- See Also:
-
toObjectAsync
Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the defaultJsonSerializer. Each time this method is called, the content is deserialized and a new instance of typeTis returned. So, calling this method repeatedly to convert the underlying data source into the same type is not recommended.The type, represented by
TypeReference, can either be a generic or non-generic type. If the type is generic create a sub-type ofTypeReference, if the type is non-generic useTypeReference.createInstance(Class).Note: This method first looks for a
JsonSerializerProviderimplementation on the classpath. If no implementation is found, a default Jackson-based implementation will be used to deserialize the object.Get a non-generic Object from the BinaryData
final Person data = new Person().setName("John"); // Ensure your classpath have the Serializer to serialize the object which implement implement // com.azure.core.util.serializer.JsonSerializer interface. // Or use Azure provided libraries for this. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson BinaryData binaryData = BinaryData.fromObject(data); Disposable subscriber = binaryData.toObjectAsync(TypeReference.createInstance(Person.class)) .subscribe(person -> System.out.println(person.getName())); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();Get a generic Object from the BinaryData
final Person person1 = new Person().setName("John"); final Person person2 = new Person().setName("Jack"); List<Person> personList = new ArrayList<>(); personList.add(person1); personList.add(person2); BinaryData binaryData = BinaryData.fromObject(personList); Disposable subscriber = binaryData.toObjectAsync(new TypeReference<List<Person>>() { }) .subscribe(persons -> persons.forEach(person -> System.out.println(person.getName()))); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();- Type Parameters:
T- Type of the deserialized Object.- Parameters:
typeReference- TheTypeReferencerepresenting the Object's type.- Returns:
- A
MonoofObjectrepresenting the JSON deserializedBinaryData. - Throws:
NullPointerException- IftypeReferenceis null.- See Also:
-
toObjectAsync
Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the passedObjectSerializer. Each time this method is called, the content is deserialized and a new instance of typeTis returned. So, calling this method repeatedly to convert the underlying data source into the same type is not recommended.The type, represented by
Class, should be a non-generic class, for generic classes usetoObject(TypeReference, ObjectSerializer).The passed
ObjectSerializercan either be one of the implementations offered by the Azure SDKs or your own implementation.Azure SDK implementations
Get a non-generic Object from the BinaryData
final Person data = new Person().setName("John"); // Provide your custom serializer or use Azure provided serializers. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer BinaryData binaryData = BinaryData.fromObject(data, serializer); Disposable subscriber = binaryData.toObjectAsync(Person.class, serializer) .subscribe(person -> System.out.println(person.getName())); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();- Type Parameters:
T- Type of the deserialized Object.- Parameters:
clazz- TheClassrepresenting the Object's type.serializer- TheObjectSerializerused to deserialize object.- Returns:
- A
MonoofObjectrepresenting the deserializedBinaryData. - Throws:
NullPointerException- Ifclazzorserializeris null.- See Also:
-
toObjectAsync
Returns anObjectrepresentation of thisBinaryDataby deserializing its data using the passedObjectSerializer. Each time this method is called, the content is deserialized and a new instance of typeTis returned. So, calling this method repeatedly to convert the underlying data source into the same type is not recommended.The type, represented by
TypeReference, can either be a generic or non-generic type. If the type is generic create a sub-type ofTypeReference, if the type is non-generic useTypeReference.createInstance(Class).The passed
ObjectSerializercan either be one of the implementations offered by the Azure SDKs or your own implementation.Azure SDK implementations
Get a non-generic Object from the BinaryData
final Person data = new Person().setName("John"); // Provide your custom serializer or use Azure provided serializers. // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://central.sonatype.com/artifact/com.azure/azure-core-serializer-json-gson final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer BinaryData binaryData = BinaryData.fromObject(data, serializer); Disposable subscriber = binaryData .toObjectAsync(TypeReference.createInstance(Person.class), serializer) .subscribe(person -> System.out.println(person.getName())); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();Get a generic Object from the BinaryData
final Person person1 = new Person().setName("John"); final Person person2 = new Person().setName("Jack"); List<Person> personList = new ArrayList<>(); personList.add(person1); personList.add(person2); // Provide your custom serializer or use Azure provided serializers. // https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-jackson or // https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-gson final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer BinaryData binaryData = BinaryData.fromObject(personList, serializer); Disposable subscriber = binaryData .toObjectAsync(new TypeReference<List<Person>>() { }, serializer) // retains the generic type information .subscribe(persons -> persons.forEach(person -> System.out.println(person.getName()))); // So that your program wait for above subscribe to complete. TimeUnit.SECONDS.sleep(5); subscriber.dispose();- Type Parameters:
T- Type of the deserialized Object.- Parameters:
typeReference- TheTypeReferencerepresenting the Object's type.serializer- TheObjectSerializerused to deserialize object.- Returns:
- A
MonoofObjectrepresenting the deserializedBinaryData. - Throws:
NullPointerException- IftypeReferenceorserializeris null.- See Also:
-
toStream
Returns anInputStreamrepresentation of thisBinaryData.Get an InputStream from the BinaryData
final byte[] data = "Some Data".getBytes(StandardCharsets.UTF_8); BinaryData binaryData = BinaryData.fromStream(new ByteArrayInputStream(data), (long) data.length); final byte[] bytes = new byte[data.length]; try (InputStream inputStream = binaryData.toStream()) { inputStream.read(bytes, 0, data.length); System.out.println(new String(bytes)); }- Returns:
- An
InputStreamrepresenting theBinaryData.
-
toByteBuffer
Returns a read-onlyByteBufferrepresentation of thisBinaryData.Attempting to mutate the returned
ByteBufferwill throw aReadOnlyBufferException.Get a read-only ByteBuffer from the BinaryData
final byte[] data = "Some Data".getBytes(StandardCharsets.UTF_8); BinaryData binaryData = BinaryData.fromBytes(data); final byte[] bytes = new byte[data.length]; binaryData.toByteBuffer().get(bytes, 0, data.length); System.out.println(new String(bytes));
- Returns:
- A read-only
ByteBufferrepresenting theBinaryData.
-
toFluxByteBuffer
Returns the content of thisBinaryDatainstance as a flux ofByteBuffers. The content is not read from the underlying data source until theFluxis subscribed to.- Returns:
- the content of this
BinaryDatainstance as a flux ofByteBuffers.
-
writeTo
Writes the contents of thisBinaryDatato the givenOutputStream.This method does not close the
OutputStream.The contents of this
BinaryDatawill be written without buffering. If the underlying data source isn'tisReplayable(), after this method is called theBinaryDatawill be consumed and can't be read again. If it needs to be read again, usetoReplayableBinaryData()to create a replayable copy.- Parameters:
outputStream- TheOutputStreamto write the contents of thisBinaryDatato.- Throws:
NullPointerException- IfoutputStreamis null.IOException- If an I/O error occurs.
-
writeTo
Writes the contents of thisBinaryDatato the givenWritableByteChannel.This method does not close the
WritableByteChannel.The contents of this
BinaryDatawill be written without buffering. If the underlying data source isn'tisReplayable(), after this method is called theBinaryDatawill be consumed and can't be read again. If it needs to be read again, usetoReplayableBinaryData()to create a replayable copy.- Parameters:
channel- TheWritableByteChannelto write the contents of thisBinaryDatato.- Throws:
NullPointerException- Ifchannelis null.IOException- If an I/O error occurs.
-
writeTo
Writes the contents of thisBinaryDatato the givenAsynchronousByteChannel.This method does not close the
AsynchronousByteChannel.The contents of this
BinaryDatawill be written without buffering. If the underlying data source isn'tisReplayable(), after this method is called theBinaryDatawill be consumed and can't be read again. If it needs to be read again, usetoReplayableBinaryDataAsync()to create a replayable copy.- Parameters:
channel- TheAsynchronousByteChannelto write the contents of thisBinaryDatato.- Returns:
- A
Monothe completes once content has been written or had an error writing. - Throws:
NullPointerException- Ifchannelis null.
-
writeTo
Writes the contents of thisBinaryDatato the givenJsonWriter.This method does not close or flush the
JsonWriter.The contents of this
BinaryDatawill be written without buffering. If the underlying data source isn'tisReplayable(), after this method is called theBinaryDatawill be consumed and can't be read again. If it needs to be read again, usetoReplayableBinaryData()to create a replayable copy.- Parameters:
jsonWriter- TheJsonWriterto write the contents of thisBinaryDatato.- Throws:
NullPointerException- IfjsonWriteris null.IOException- If an I/O error occurs during writing.
-
getLength
Returns the length of the content, if it is known. The length can benullif the source did not specify the length or the length cannot be determined without reading the whole content.- Returns:
- the length of the content, if it is known.
-
isReplayable
public boolean isReplayable()Returns a flag indicating whether the content can be repeatedly consumed using all accessors includingtoStream()andtoFluxByteBuffer()Replayability does not imply thread-safety. The caller must not use data accessors simultaneously regardless of what this method returns.
BinaryData binaryData = binaryDataProducer(); if (!binaryData.isReplayable()) { binaryData = binaryData.toReplayableBinaryData(); } streamConsumer(binaryData.toStream()); streamConsumer(binaryData.toStream());Mono.fromCallable(this::binaryDataProducer) .flatMap(binaryData -> { if (binaryData.isReplayable()) { return Mono.just(binaryData); } else { return binaryData.toReplayableBinaryDataAsync(); } }) .flatMap(replayableBinaryData -> fluxConsumer(replayableBinaryData.toFluxByteBuffer()) .then(fluxConsumer(replayableBinaryData.toFluxByteBuffer()))) .subscribe();- Returns:
- a flag indicating whether the content can be repeatedly consumed using all accessors.
-
toReplayableBinaryData
Converts theBinaryDatainto aBinaryDatathat is replayable, i.e. content can be consumed repeatedly using all accessors includingtoStream()andtoFluxByteBuffer()A
BinaryDatathat is already replayable is returned as is. Otherwise techniques like marking and resetting a stream or buffering in memory are employed to assure replayability.Replayability does not imply thread-safety. The caller must not use data accessors of returned
BinaryDatasimultaneously.BinaryData binaryData = binaryDataProducer(); if (!binaryData.isReplayable()) { binaryData = binaryData.toReplayableBinaryData(); } streamConsumer(binaryData.toStream()); streamConsumer(binaryData.toStream());- Returns:
- Replayable
BinaryData.
-
toReplayableBinaryDataAsync
Converts theBinaryDatainto aBinaryDatathat is replayable, i.e. content can be consumed repeatedly using all accessors includingtoStream()andtoFluxByteBuffer()A
BinaryDatathat is already replayable is returned as is. Otherwise techniques like marking and resetting a stream or buffering in memory are employed to assure replayability.Replayability does not imply thread-safety. The caller must not use data accessors of returned
BinaryDatasimultaneously.Mono.fromCallable(this::binaryDataProducer) .flatMap(binaryData -> { if (binaryData.isReplayable()) { return Mono.just(binaryData); } else { return binaryData.toReplayableBinaryDataAsync(); } }) .flatMap(replayableBinaryData -> fluxConsumer(replayableBinaryData.toFluxByteBuffer()) .then(fluxConsumer(replayableBinaryData.toFluxByteBuffer()))) .subscribe();- Returns:
- A
MonoofBinaryDatarepresenting the replayableBinaryData.
-