I have a below code in which my zip file is getting created on the server machine, i want the zip file to be created in the local machine, below is my code, please check the below code and let me know if anybody has a solution for it .
<%!
public static void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {
System.out.println("Writing '" + fileName + "' to zip file");
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
%>
<%
String imgID = request.getParameter("iID").toString();
String epsFile = request.getParameter("epsNm").toString();
String ZipFile = imgID + ".zip";
//FileOutputStream fos = new FileOutputStream("d:/" + ZipFile);
FileOutputStream fos = new FileOutputStream(ZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
File temp = new File(imgID);
String absolutePath = temp.getAbsolutePath();
System.out.println("filepath" + absolutePath);
String relativeWebPath = "CoverCapPDF/"+ imgID;
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
System.out.println("absoluteDiskPath" + absoluteDiskPath);
String relativeWebPathEPS = "eps/"+ epsFile;
String absoluteDiskPathEPS = getServletContext().getRealPath(relativeWebPathEPS);
System.out.println("absoluteDiskPath" + absoluteDiskPathEPS);
String file1Name = absoluteDiskPath;
String file2Name = absoluteDiskPathEPS;
String file3Name = "file2.txt";
addToZipFile(file1Name, zos);
addToZipFile(file2Name, zos);
zos.close();
fos.close();
%>
please help me :)
I am assuming you are dealing with a web application which uses JSP (since the above syntax suggests the same). The answer then is you cannot.
What you can do is
Create the file at the server and ask the client to download refer here
Create an applet and the applet can have the zip code (though not recommended for security reasons)
First of all, you should not use a JSP for this, but a servlet. JSPs are view components, whose role is to generate HTML markup using the JSP EL, the JSTL and other custom tags, but no scriptlet.
Second: you're writing to a FileOutputStream. that obviously writes your zip entries to a file. You want to write your zip entries to the HTTP response. You should thus use the response output stream to write your zip entries.
To tell the browser that you're sending what should be saved as a zip file, use
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
(this should be called before sending anything to the response output stream)
Related
My app is a tender document system where each tender number has one or more pdf files attached.
application is done in java ee using struts and mysql.
in a database table the paths of each related pdf file for a tender number is stores.
I want to get all the pdf files and create a single ZIP file for each tender number so that user can download that zip file and have all the related documents in a single click.
I tried Google and found something called ZipOutputStream but i cannot understand how to use this in my application.
You're almost there... This is a small example of how to use ZipOutputStream... let's asume that you have a JAVA helper H that returns database records with pdf file paths (and related info):
FileOutputStream zipFile = new FileOutputStream(new File("xxx.zip"));
ZipOutputStream output = new ZipOutputStream(zipFile);
for (Record r : h.getPdfRecords()) {
ZipEntry zipEntry = new ZipEntry(r.getPdfName());
output.putNextEntry(zipEntry);
FileInputStream pdfFile = new FileInputStream(new File(r.getPath()));
IOUtils.copy(pdfFile, output); // this method belongs to apache IO Commons lib!
pdfFile.close();
output.closeEntry();
}
output.finish();
output.close();
Checkout this code, here you can easily create a zip file directory:
public class CreateZipFileDirectory {
public static void main(String args[])
{
try
{
String zipFile = "C:/FileIO/zipdemo.zip";
String sourceDirectory = "C:/examples";
//create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fout = new FileOutputStream(zipFile);
ZipOutputStream zout = new ZipOutputStream(fout);
File dir = new File(sourceDirectory);
if(!dir.isDirectory())
{
System.out.println(sourceDirectory + " is not a directory");
}
else
{
File[] files = dir.listFiles();
for(int i=0; i < files.length ; i++)
{
System.out.println("Adding " + files[i].getName());
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
}
}
zout.close();
System.out.println("Zip file has been created!");
}
catch(IOException ioe)
{
System.out.println("IOException :" + ioe);
}
}
}
I want to write a unit test to test creating .zip file from two .doc files. BU I take an error: Error creating zip file: java.io.FileNotFoundException: D:\file1.txt (The system cannot find the file specified)
My code is here:
#Test
public void testIsZipped() {
String actualValue1 = "D:/file1.txt";
String actualValue2 = "D:/file2.txt";
String zipFile = "D:/file.zip";
String[] srcFiles = { actualValue1, actualValue2 };
try {
// create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
for (int i = 0; i < srcFiles.length; i++) {
File srcFile = new File(srcFiles[i]);
FileInputStream fis = new FileInputStream(srcFile);
// begin writing a new ZIP entry, positions the stream to the
// start of the entry data
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
// close the ZipOutputStream
zos.close();
}
catch (IOException ioe) {
System.out.println("Error creating zip file: " + ioe);
}
String result = zos.toString();
assertEquals("D:/file.zip", result);
}
Can I get name of zip file from zos to test, How to understand to pass the test? Can anybody help me to solve this error? Thank you.
First, are your files created in a previous test method? If yes consider that junit tests do not execute in the order you defined your test methods, have a look at this:
How to run test methods in specific order in JUnit4?
Second, you could add a debugging line:
File srcFile = new File(srcFiles[i]);
System.out.append(srcFile+ ": " + srcFile.exists() + " " + srcFile.canRead());
After you solve the exception you will run into this problem, the test will fail:
String result = zos.toString();
assertEquals("D:/file.zip", result);
zos.toString() will return something like: "java.util.zip.ZipOutputStream#1ae369b7" which will not be equal to "D:/file.zip".
String zipFile = "D:/file.zip";
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
System.out.println(zos.toString());
if(!ErmUtil.isNull(listOfActualFilePaths) && listOfActualFilePaths.size()>0){
FileOutputStream fos = new FileOutputStream("/smiles/wrk/attachments/ermWeb/taxation/testing.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
Iterator itrOnFNames = listOfActualFilePaths.iterator();
while (itrOnFNames.hasNext()) {
StringBuffer ActualPath = (StringBuffer) itrOnFNames.next();
addToZipFile(ActualPath.toString(), zos);
}
zos.close();//Closing Both Streams
fos.close();
}
public void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {
System.out.println("Writing '" + fileName + "' to zip file");
File file = new File(fileName);
int index = fileName.lastIndexOf("/");
String fileNameForZip = fileName.substring(index+1);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(fileNameForZip);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
I am using above code, to save zip-ed file on a specific location. But what i want to do is that, instead of saving that file, it get downloaded directly.
Edit 1
See If I want to download a zip file,then according to above code, on path /smiles/wrk/attachments/ermWeb/taxation/testing.zip it will be saved first,then from that folder, I(server) can send it to client(Computer).
But I don't want to save it on the specified path,Instead of "saving first to folder and then sending to client", I directly want to send it to client.
<% // Set the content type based to zip
response.setContentType("Content-type:text/zip");
response.setHeader("Content-Disposition", "attachment; filename=mytest.zip");
// List of files to be downloaded
List files = new ArrayList();
files.add(new File("C:/first.txt"));
files.add(new File("C:/second.txt"));
files.add(new File("C:/third.txt"));
ServletOutputStream out1 = response.getOutputStream();
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(out1));
for (Object file : files)
{
//System.out.println("Adding file " + file.getName());
System.out.println("Adding file " + file.getClass().getName());
//zos.putNextEntry(new ZipEntry(file.getName()));
zos.putNextEntry(new ZipEntry(file.getClass().getName()));
// Get the file
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (Exception E) {
// If the file does not exists, write an error entry instead of file contents
//zos.write(("ERROR: Could not find file " + file.getName()).getBytes());
zos.write(("ERROR: Could not find file" +file.getClass().getName()).getBytes());
zos.closeEntry();
//System.out.println("Could not find file "+ file.getAbsolutePath());
continue;
}
BufferedInputStream fif = new BufferedInputStream(fis);
// Write the contents of the file
int data = 0;
while ((data = fif.read()) != -1) {
zos.write(data);
}
fif.close();
zos.closeEntry();
//System.out.println("Finished adding file " + file.getName());
System.out.println("Finished adding file " + file.getClass().getName());
}
zos.close();
%>
this is my actualy program , want to zip multiple file and then downloading it , is wat i am doing the way is right or wrong , am new to JAVA programming , can you help me out ???
Your for loop should look like this:
for (File file : files) {
...
or
for (String file : files) {
...
The way you declared file variable, makes compiler assume it's an Object, and not a File instance. Thus, you get compilation error, because there is no FileInputStream constructor accepting an Object. The file must either be a File or a String containing absolute path to a file.
Another error is the way, you're passing file's name to the ZipEntry.
Using:
file.getClass().getName()
will result in "java.io.File" or "java.lang.String", and not the file name.
To set the proper name of the file, use File#getName().
I tried creating a pdf file out of another one(in my local drive) using java.io. The thing is a file with a .pdf extension got created but im unable to open the file, it says the file is already in use and most importantly the size of the file is too large and it keeps on increasing (origin file size : 5,777kB and the newly created one file size as of now is 38,567kB). Im not that much of skilled java programmer but still i would appreciate if anyone can give me an explanation ..
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
for (int b = fis.read(); b != -1;) {
fos.write(b);
}
Simple use,
FileUtils.copyFile()
you meet the two problems
first,you have to close the resource: fis and fos,or it will say the file already in use
second,you have to use the byte[] to receive the data because pdf file is organized in byte arrays
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
byte[] buff=new byte[1024];
int len;
while((len=fis.read(buff))>=0) {
fos.write(buff,0,len);
}
fis.close();
fos.close();