A Zip file contains other files inside it. A docx file is essentially a zip file with a custom extension. Whenever you insert an image or other file to it is saves that file inside the zip file and a path to the new file is added in its document.xml file which is the main file that makes docx file.
Let's see how we can achieve the functionality of adding a file to an existing zip file.
If zipFileName is path to existing zip file and fileName, the File object to be added, we can use the following method to add fileName to zipFileName
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class AddFileToZip {
public static void appendFileToExistingZip(String zipFileName,File fileName) throws IOException{
if(!file.isFile()){
return;
}
URLConnection conn = new URL("zip:" + zipFileName + "\\" + file.getName()).openConnection();
byte[] buf = new byte[1024];
// Compress the files
InputStream in = new FileInputStream(file);
// Add file to output stream.
OutputStream os = conn.getOutputStream();
// Transfer bytes from the stream to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
os.write(buf, 0, len);
}
in.close();
os.close();
}
}
Let's see how we can achieve the functionality of adding a file to an existing zip file.
If zipFileName is path to existing zip file and fileName, the File object to be added, we can use the following method to add fileName to zipFileName
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class AddFileToZip {
public static void appendFileToExistingZip(String zipFileName,File fileName) throws IOException{
if(!file.isFile()){
return;
}
URLConnection conn = new URL("zip:" + zipFileName + "\\" + file.getName()).openConnection();
byte[] buf = new byte[1024];
// Compress the files
InputStream in = new FileInputStream(file);
// Add file to output stream.
OutputStream os = conn.getOutputStream();
// Transfer bytes from the stream to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
os.write(buf, 0, len);
}
in.close();
os.close();
}
}