Introduction#
MxPack is a modern Java library for reading and writing the MessagePack serialization format.
The Kotlin examples on this website use MxPack's Kotlin integration.
Example#
The following code writes a string and number to path
, then reads them back:
var out = FileChannel.open(path, WRITE, CREATE);
try (var writer = MessageWriter.of(out)) { //(1)
writer.write("Hello, MxPack!"); //(2)
writer.write(42); //(3)
}
var in = FileChannel.open(path);
try (var reader = MessageReader.of(in)) { //(4)
var string = reader.readString(); //(5)
var number = reader.readInt(); //(6)
}
- Creates a
MessageWriter
that writes toout
. Thetry
block ensures that the writer is always closed and not used thereafter. - Encodes string
"Hello, MxPack!"
and writes it toout
. - Encodes number
42
and writes it toout
. - Creates a
MessageReader
that reads fromin
. Thetry
block ensures that the reader is always closed and not used thereafter. - Reads a string from
in
and decodes it to"Hello, MxPack!"
. - Reads a number from
in
and decodes it to42
.
val out = FileChannel.open(path, WRITE, CREATE)
MessageWriters.of(out).use { writer -> //(1)
writer.write("Hello, MxPack!") //(2)
writer.write(42) //(3)
}
val ch = FileChannel.open(path)
MessageReaders.of(ch).use { reader -> //(4)
val string = reader.readString() //(5)
val number = reader.readInt() //(6)
}
- Creates a
MessageWriter
that writes toout
. The preferred Kotlin way to create a writer isMessageWriters.of()
(note the plural form). Theuse {}
block ensures that the writer is always closed and not used thereafter. - Encodes string
"Hello, MxPack!"
and writes it toout
. - Encodes number
42
and writes it toout
. - Creates a
MessageReader
that reads fromin
. The preferred Kotlin way to create a reader isMessageReaders.of()
(note the plural form). Theuse {}
block ensures that the reader is always closed and not used thereafter. - Reads a string from
in
and decodes it to"Hello, MxPack!"
. - Reads a number from
in
and decodes it to42
.
License#
Copyright 2024 the MxPack project authors
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.