How to get Java byte array into Matlab
Ältere Kommentare anzeigen
Dear All,
I am using a Java DataInputStream to get data over TCPIP. To get the data e.g by the method readFully(byte[] b, int off, int len), I have to pass a byte[] array to the Java method. So far I am using a java class DataInputReader that outputs a byte array (see below). Is there a way to do that (and how) directly in Matlab without calling an external java class ? In other word, how a pass to a java class a handle to a Matlab array ?
Thanks for your help
Patrick
****
import java.io.*;
class DataInputReader {
private DataInput m_data_input;
public DataInputReader(DataInput data_input) {
m_data_input = data_input;
}
public byte[] readBuffer(int length) {
byte[] buffer = new byte[length];
try {
m_data_input.readFully(buffer, 0, length);
}
catch (StreamCorruptedException e) {
System.out.println("Stream Corrupted Exception Occured");
buffer = new byte[0];
}
catch (EOFException e) {
System.out.println("EOF Reached");
buffer = new byte[0];
}
catch (IOException e) {
System.out.println("IO Exception Occured");
buffer = new byte[0];
}
return buffer;
}
}
Antworten (1)
Harsh Mahalwar
am 28 Feb. 2024
Bearbeitet: Harsh Mahalwar
am 28 Feb. 2024
Hi Patrick,
As I can understand, you are trying to implement the “DataInputReader” class into MATLAB. Also, you are interested in understanding how to retrieve Java byte arrays in MATLAB.
Please refer to the following MathWorks documentation for more information on handling data in Java:
- Handle Data Returned from Java Methods: https://www.mathworks.com/help/matlab/matlab_external/handling-data-returned-from-java-methods.html
You can import Java datatypes into MATLAB and use them along with your MATLAB arrays, here’s an example:
import java.lang.*
sampleArray = javaArray('java.lang.Byte', 1, 19);
for i = 1:numel(sampleArray(1, :))
sampleArray(1, i) = Byte(randi(100, 1));
end
The above MATLAB script creates a sample Java ByteArray (in MATLAB Java ByteArrays use int8 datatype).
Please refer to the following MathWorks documentation for more information on classes and error handling in MATLAB:
- Creating user-defined classes in MATLAB: https://www.mathworks.com/help/matlab/matlab_oop/user-defined-classes.html
- Execute statements and catch resulting errors: https://www.mathworks.com/help/matlab/ref/try.html
I hope this helps, thanks!
Kategorien
Mehr zu Call Java from MATLAB finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!