I am trying to convert a file to byte array and send through socket to my server written in python. But when I try convert the file to byte I get this error -
java.lang.ArrayIndexOutOfBoundsException: length=1048576; regionStart=1048576; regionLength=1048576
Code that runs when I press the upload button -
Button upload = binding.button2;
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//I have stored the path of the file which is a string in a arraylist
//"files" is an obj of that ArrayList
System.out.println("Inside OnClick" + files.size());
try {
for (int i = 0; i < files.size(); i++) {
Path path = Paths.get(files.get(i));
DataInputStream in = new DataInputStream(new FileInputStream(files.get(i)));
int size = (int)Files.size(path);
int iter = size/(1024 * 1024) + 1;
System.out.println(size + " " + iter);
Thread send = new Thread(new Runnable() {
@Override
public void run() {
try {
ByteBuffer data = ByteBuffer.allocate(1048576); // 1048576 = 1MB
DataOutputStream out = new DataOutputStream(SocketHandler.getSocket().getOutputStream());
out.write("upl sample.mkv".getBytes(StandardCharsets.UTF_8));
Thread.sleep(200);
out.write(String.valueOf(size).getBytes(StandardCharsets.UTF_8));
Thread.sleep(200);
int off = 0;
for(int j = 0;j < iter;j++){
if(j == iter - 1){
off += in.read(data.array(),off,size - off);
}
else {
// This where I get the error
//And the error is always on the second iteration
off += in.read(data.array(), off, 1048576);
}
data.clear();
}
System.out.println(off);
}catch(IOException | InterruptedException e){
e.printStackTrace();
}
}
});
send.start();
send.join();
}
}catch(IOException | InterruptedException e){
e.printStackTrace();
}
}
});
This is what was printed in logs -
D/ViewRootImpl@1d9e105[MainActivity2]: ViewPostIme pointer 1
I/System.out: Inside OnClick1
I/System.out: 259728246 248
E/AndroidRuntime: FATAL EXCEPTION: Thread-7
Process: com.iot.ftpserver, PID: 30412
java.lang.ArrayIndexOutOfBoundsException: length=1048576; regionStart=1048576; regionLength=1048576
at java.util.Arrays.checkOffsetAndCount(Arrays.java:135)
at libcore.io.IoBridge.read(IoBridge.java:496)
at java.io.FileInputStream.read(FileInputStream.java:307)
at java.io.DataInputStream.read(DataInputStream.java:152)
at com.iot.ftpserver.ui.gallery.GalleryFragment$1$1.run(GalleryFragment.java:104)
at java.lang.Thread.run(Thread.java:764)
I/Process: Sending signal. PID: 30412 SIG: 9
Can someone please help me? Thanks in advance