Welcome back.
Now let's create the Loadmodel function.
Outside the initialize function, create a new function named as load mode.
This function takes a string.
Name it as file name as a parameter and returns byte buffer.
This function loads a file from assets and returns it as a byte buffer.
Let me write this comment below.
Returns null if loading fails, so I use this question mark.
So here we need to load the model and returns it as byte buffer.
Uses memory mapping for efficient file access.
Let me start by opening the model file.
So here return return try.
Let me try to open the file model file or my model whatever you want.
Context dot dot open folder.
What's the name of the folder?
Is the file name parameter that it's best to do the conversion of the file to bytebuffer.
We need to start with the input stream equals to file input stream and set the model file dot file descriptor.
The first line appends the file from the app's assets folder.
Using assets file descriptor provides access to the file descriptor, start offset, and declared length,
while the second line creates a file input stream from the file descriptor.
This allows reading the file as a stream of bytes.
So here.
Step number two reading the model file as stream byte stream of bytes.
The third step is the file channel val file channel equals to input stream dot channel file channel
dot map.
We need to pass three parameters the file channel, the start of set and the declared length or size
of the file channel.
Alt+ enter to import the file channel.
Obtains a file channel from the input stream, and the file channel provides methods for file operations,
including memory mapping.
I want from you to write those those comments below because they are very important okay.
And helps you to understand the code, the file channel.
Here we are.
We are making a memory map of the file.
Mapping the file to the memory okay.
File channel dot map mode read only maps the file as read only model file dot start offset starting
position in the file usually zero and the declared length.
The length of the file to the map.
Returns a map byte buffer that directly represents the file content in the Memory.
Why we need memory mapping we need for file content is loaded on demand.
Lazy loading, which is efficient memory mapping is used for fast access direct memory access without
copying data and OS managed because operating system handles paging and caching.
So those are the advantages of mapping and memory mapping.
Okay, now we need to catch any errors that may result from this mapping and this conversion.
So for that we need to start with catch here E exception.
And we need to log e tag and load it model print the message and return null okay.
So this is the load model function.
This is how we load the model and convert it as byte buffer.