Hi,
I'll quickly explain what i am trying to do before telling the problem i am facing.
Requirement:
- Store the contents of a file into an object.
- Send the object through HTTP socket to another client server.
- Have the server fetch the file contents from the object.
- Compress it.
- Store the compressed file's content back into the object.
- Send the new object back to the server.
- Server fetched the compressed file contents from the recieved object and writes to a zip file
Problem:
The final output file [the zip file] is corrupted. On opening it comes up as an invalid archive.
Observations:
The problem seems to be in how i store the file contents in the object.
This is because the client, while compressing, creates a temp zip file which it then reads and stores into the object.
This temporary file was a valid zip, but the contents seemed to be corrupted.
Code Snippets
I am currently storing the file contents as a String in the object.
Getting the file contents into the string like the following:
fileContents = FileUtils.readFileToString(new File(path), Charset.forName("UTF-8"));
Sending the object over the socket using :
outStream.writeObject(msg);
outStream.flush();
where outStream is an ObjectOutputStream
.
Reading the object on the client using ObjectInputStream
:
Job job = (Job) in.readObject();
Compressing using the following :
FileOutputStream fos = new FileOutputStream(job.getFileName() + ".zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze= new ZipEntry(job.getFileName());
zos.putNextEntry(ze);
byte[] bytes = job.getFileContents().getBytes(Charset.forName("UTF-8"));
zos.write(bytes,0,bytes.length);
zos.closeEntry();
zos.close();
Using similar techniques to store the compressed file contents back to the object, send it and recieve it back at the server side.
After recieveing the object, the contents are written to a file likewise :
FileOutputStream fOut = new FileOutputStream(newFile);
byte[] bytes = completedJob.getFileContents().getBytes(Charset.forName("UTF-8"));
fOut.write(bytes);
fOut.close();
Any help would be greatly appreciated.
Thanks,
Aravind