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 :)
write; creatingFileOutputStreamwith the 1-arg String (or File) ctor truncates any existing file. You should create one stream increateFilethenwriteall buffers to that one stream, and thencloseor at leastflushit; in some filesystems not flushing or closing might lose data.< 512as an EOF indication. A short read can happen at any time, and a file can be a multiple of 512 bytes. You don't need a superimposed packetising protocol just to transfer a file: the standard Java copy loop will do. And you neither need nor want to assemble all the bytes of a file before writing any of it. Unclear what you're asking.