I'm writing a file transfer protocol, in which files are sent between server and client in packets of 512 bytes each. If a file is larger than that size, the file will be split into multiple packets. I'm doing the splitting ok I think, but I'm having trouble re-assembling the files. If the file is smaller than 512 byte (one packet) the assembly process works, but if the file is larger, only the last packet to arrive is being written to the file.
Here is the code of the FileAssembler:
public class FileAssambler {
List<byte[]> bytesList;
private String name;
boolean finished=false;
private FileOutputStream fileOutputStream;
public FileAssambler(String name){
bytesList = new ArrayList<byte[]>();
this.name = name;
}
public void addBytes(byte[] bytes){
if(bytes.length<512)
finished=true;
bytesList.add(bytes);
}
public boolean isFinished(){
return finished;
}
public void createFile() throws IOException{
Iterator<byte[]> it = bytesList.iterator();
while(it.hasNext())
writeBytesToFile(it.next());
}
private void writeBytesToFile(byte[] bytes){
try{
fileOutputStream = new FileOutputStream(name);
fileOutputStream.write(bytes);
}catch(IOException e){
e.printStackTrace();
}
}
}
I think that the fileOutputStream.write(bytes) simply replaces the existing bytes with the new one, what is the alternative to writing into a file?
How do I combine multiple byte[] arrays into a single file?
Thanks in advance :)