Reputation: 175
In this code when the loop is finished the array is filled with the same value everywhere. After some debugging I noticed that at every add() the array is filled up entirely with the same value.
List<byte[]> datas = new ArrayList<byte[]>();
// CODE ... //
FileInputStream fis = new FileInputStream(file);
byte[] buff = new byte[2];
int n;
while((n=fis.read(buff))!=-1){
this.datas.add(buff);
}
fis.close();
I tried the same code with an array of String and it worked correctly...
Why is this happening, and how can I fix it?
Upvotes: 0
Views: 83
Reputation: 721
You're filling the ArrayList with the same instance of the byte[] buff variable. So each time you modify buff (in fis.read(buff) ) you're actually modifying all the items in the ArrayList.
Try creating a new byte[] in each iteartion:
List<byte[]> datas = new ArrayList<byte[]>();
// CODE ... //
FileInputStream fis = new FileInputStream(file);
byte[] buff = new byte[2];
int n
while((n=fis.read(buff))!=-1){
this.datas.add(buff);
buff = new byte[2];
}
fis.close();
Upvotes: 1