Read Zip File and output it to the Stream

Hi,
I really need help with this topic. I need to write a function which as input read the zip file (inside: jpeg, mp3, xml)
and as output provide the output Stream of this zip file.
public OutputStream readZipToStream(String sourceZipFile) { ....}
I've tried something....
public static OutputStream    readZipToStream(String src, HttpServletResponse response) throws Exception {
        File fsrc = null;
        ZipOutputStream out = null;
        byte buffer [] = null;
        FileInputStream in = null;
        try {
            buffer = new byte[BUFFER_CREATE];
            fsrc = new File(src);
            out = new ZipOutputStream(response.getOutputStream());
            ZipEntry zipAdd = new ZipEntry(fsrc.getName());
            zipAdd.setTime(fsrc.lastModified());
            out.putNextEntry(zipAdd);
            // Read input & write to output
            in = new FileInputStream(fsrc);
            while (true) {
                int nRead = in.read(buffer, 0, buffer.length);
                if (nRead <= 0)
                    break;
                out.write(buffer, 0, nRead);
            out.flush();
            in.close();
        } catch (IOException ioe) {
            logger.error("Zip Exception: " + ioe.getMessage());
            ioe.printStackTrace();
            throw ioe;
        return out;
    } But the problem with this code when it returns ( I called from servlet: bellow)
it ask user to save the file as servlet.jsp file. So I would have to rename it to zip file later.
What I want to achive is it would ask to save zip file from the stream as name of the original zip file (if that is possible)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
OutputStream stream = null;
response.setContentType("application/zip");
target = mount_media + File.separator + "test_swf.zip";       
try {
stream = ZipUtil.readZipToStream(target, response);
} catch (Exception ex) {
        System.out.println(ex.getMessage());
    } finally {
if(stream != null) {
            stream.close();
%>
<%@page import="java.io.File" %>
<%@page import="java.io.OutputStream" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
</body>
</html>

Hi oleg_s ,
There's a contradiction of content in your JSP :
response.setContentType("application/zip");
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">The html part of your JSP seems useless for what you mean to do. Therefore, instead of a JSP, you should use a simple servlet to send your zip file.

Similar Messages

  • How can I input read a line from a file and output it into the screen?

    How can I input read a line from a file and output it into the screen?
    If I have a file contains html code and I only want the URL, for example, www24.brinkster.com how can I read that into the buffer and write the output into the screen that using Java?
    Any help will be appreciate!
    ======START FILE default.html ========
    <html>
    <body>
    <br><br>
    <center>
    <font size=4 face=arial color=#336699>
    <b>Welcome to a DerekTran's Website!</b><br>
    Underconstructions.... <br>
    </font> </center>
    <font size=3 face=arial color=black> <br>
    Hello,<br>
    <br>
    I've been using the PWS to run the website on NT workstation 4.0. It was working
    fine. <br>
    The URL should be as below: <br>
    http://127.0.0.1/index.htm or http://localhost/index.htm
    <p>And suddently, it stops working, it can't find the connection. I tried to figure
    out what's going on, but still <font color="#FF0000">NO CLUES</font>. Does anyone
    know what's going on? Please see the link for more.... I believe that I setup
    everything correctly and the bugs still flying in the server.... <br>
    Thank you for your help.</P>
    </font>
    <p><font size=3 face=arial color=black>PeerWebServer.doc
    <br>
    <p><font size=3 face=arial color=black>CannotFindServer.doc
    <br>
    <p><font size=3 face=arial color=black>HOSTS file is not found
    <br>
    <p><font size=3 face=arial color=black>LMHOSTS file
    <br>
    <p><font size=3 face=arial color=black>How to Setup PWS on NT
    <BR>
    <p><font size=3 face=arial color=black>Issdmin doc</BR>
    Please be patient while the document is download....</font>
    <font size=3 face=arial color=black><br>If you have any ideas please drop me a
    few words at [email protected] </font><br>
    <br>
    <br>
    </p>
    <p><!--#include file="Hits.asp"--> </p>
    </body>
    </html>
    ========= END OF FILE ===============

    Hi!
    This is a possible solution to your problem.
    import java.io.*;
    class AddressExtractor {
         public static void main(String args[]) throws IOException{
              //retrieve the commandline parameters
              String fileName = "default.html";
              if (args.length != 0)      fileName =args[0];
               else {
                   System.out.println("Usage : java AddressExtractor <htmlfile>");
                   System.exit(0);
              BufferedReader in = new BufferedReader(new FileReader(new File(fileName)));
              StreamTokenizer st = new StreamTokenizer(in);
              st.lowerCaseMode(true);
              st.wordChars('/','/'); //include '/' chars as part of token
              st.wordChars(':',':'); //include ':' chars as part of token
              st.quoteChar('\"'); //set the " quote char
              int i;
              while (st.ttype != StreamTokenizer.TT_EOF) {
                   i = st.nextToken();
                   if (st.ttype == StreamTokenizer.TT_WORD) {          
                        if (st.sval.equals("href")) {               
                             i = st.nextToken(); //the next token (assumed) is the  '=' sign
                             i = st.nextToken(); //then after it is the href value.               
                             getURL(st.sval); //retrieve address
              in.close();
         static void getURL(String s) {     
              //Check string if it has http:// and truncate if it does
              if (s.indexOf("http://") >  -1) {
                   s = s.substring(s.indexOf("http://") + 7, s.length());
              //check if not mailto: do not print otherwise
              if (s.indexOf("mailto:") != -1) return;
              //printout anything after http:// and the next '/'
              //if no '/' then print all
                   if (s.indexOf('/') > -1) {
                        System.out.println(s.substring(0, s.indexOf('/')));
                   } else System.out.println(s);
    }Hope this helps. I used static methods instead of encapsulating everyting into a class.

  • Reading text file and output (to stdout) a list of the unique words in the

    Hi,
    I have a main method as
    main.java
    package se.tmp;
    public class Main
    public static void main( String[] args )
    WordAnalyzer.parse( args[0] );
    and text file as
    words.txt
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the requirement is like
    I need create this WordAnalyzer class, implement the parse method, and then commit the file. This method takes a single parameter, the filename of the file to parse. The method should read this file and output (to stdout) a list of the unique words in the file along with the number of times each appears in the file.
    Can anyone please help me on this?
    Thanks.

    Where are you having problems?

  • After reinstalling CS6 the bridge photo downloader isn't able to read raw files and fails to convert the raw files to DNG. Previously downloaded raw files, now DNG, open up successfully in Camera Raw 7. How do I get the photo downloader to read and conver

    After reinstalling CS6 the bridge photo downloader isn't able to read raw files and fails to convert the raw files to DNG. Previously downloaded raw files, now DNG, open up successfully in Camera Raw 7. How do I get the photo downloader to read and convert raw files. MacBook Pro with Snow Leopard. No such problem before this reinstallation.

    You should install Camera Raw 4.6.
    Visit this page and follow the instructions carefully:
    PC:    http://www.adobe.com/support/downloads/detail.jsp?ftpID=4040
    Mac:  http://www.adobe.com/support/downloads/detail.jsp?ftpID=4039
    -Noel

  • How to synchronize if one servlet read a file and anothe servlet update the

    How to synchronize if one servlet read a file and anothe servlet update the file at a time?

    Create a class that holds the reference to the file and do the whole file manipulation just in that class. than synchronize the read and write methodes. A reference to this file handler class can be stored to the servlet context in one servlet and read out from the servlet context in the other servlet.

  • Rename the zip file and send it using the Receiver Mail Adapter

    Hi,
    We have a custom module that will create multiple attachments. The result is then passed to the PayloadZipBean, which zips as per required.
    When we output this to a file adapter, we provide the file name as say "zippedfile.zip" the result is as expected.
    For example, if the custom module created 3 attachments with the names as file1.txt, file2.txt and file3.txt, the zip file zippedfile.zip, will contain 3 files as file1.txt, file2.txt and file3.txt.
    The issue that we are facing is when we use the mail adapter, the zip file is getting renamed to file1.txt.zip i.e to say that it takes the name of the main payload from the custom module (file1.txt)
    TextPayload txtpayload = message.getDocument();
    txtpayload.setContentType("text/plain");
    txtpayload.setName("file1.txt");
    moduleData.setPrincipalData(message);
    We tried using the MessageTransformbean but it doesn't seem to change the name of the file.
    Not sure where we are going wrong. Is it that the output of the payloadzipbean cannot be used and altered by MessageTransformbean?
    Is there any alternative as to rename the name of zipfiles and use it in the mail adapter?
    Appreciate any help on this regard.
    Regards,
    Shabz

    Solved.
    use Transform.ContentDisposition - attachment;filename="youfilename"
    Do read the mail adapter FAQ.
    The parameter can vary for different mail client.

  • File Adapter to read Zip file and send it as input to another webservice

    Hi,
    I have the below requirement:
    1. A service will generate 3 attachments and place it in a particular directory.
    2. SOA service has to pick those 3 files and send those files as input to another custom application which will email.
    Design :
    1. First SOA will create an archive file of those 3 attachements and then file adapter will poll for that zip file in that location and send that file as a whole to the custom application.
    Query:
    Now my question, is the above design feasible? If so, how to configure the file adapter to pass the file as input to that custom application?
    Kindly do the needful
    Thanks,
    Priya

    You can accomplish this via java embedding activity...Create a java embedding, which will create a zip file.. this java code is easy to implement..
    You can also do away with un-necessary polling file adapter.. and you can use "Synchronous File Read" operation of File Adapter.. For Sync Read, you'll have to pass the zip file name, which you can easily fetch from java embedding activity..
    Let me know, if this doesn't work.

  • Read from .txt file and output the content as two arrays

    I am using the contoured move to control the x-y stage. The trajectory datas for x and y axis are generated using my interpolation program and it is stored in a .txt file as two columns. What I want to do is read .txt file and output the content of this file as two arrays. Is there anyone has any ideas? Thanks, the .txt file is attached.
    Attachments:
    R.75.txt ‏172 KB

    Hi Awen,
    This is quite easy to do, you can merely use the "read from spreadsheet file" function to get a 2D array (2 columns and n rows) and then use the index array function to get whatever row/colums you want..
    Hope the attached VI helps you
    When my feet touch the ground each morning the devil thinks "bloody hell... He's up again!"
    Attachments:
    read sprdsheet file.vi ‏27 KB

  • Panagon and MGETDOC Application:open a doc, the doc goes to .zip file instead of going to the doc directly

    Application: FileNet content SG (Panagon) and MGETDOC(Web application)
    Issue: when open a doc, the doc goes to .zip file instead of going to the doc directly. Only this issue happens for .xlsx,docs and pptx document.
    Note: On all client machine, we are using office 2007 and IE8 browser
    Cause: On 16<sup>th</sup> July 2013, . Net framework 4.5 is install on all our GI-D desktop machines. There after the issue is started .
    Application Background: Applications built on .net framework 1.1 and it can support up to 4.0 version on client machine to view the documents through panagon and MGETDOC application. Panagon (Filenet content services) is
    not supported in .net framework 4.5 and above.
    Work around: After I had troubleshooting and tested with one of our  system which has .net framework 4.5, IE8 does not support with HTML5 and tested with IE9 and Chrome, documents were able to open successfully.
    I had removed .Net framework 4.5 uninstalled and able to open the documents w/o any issue. And also we had give the work around as if the doc goes to zip file, they open the doc by removing the . zip extension and they can save it as .xlsx or docx file and
    they can able to open file.
    Please let us know if you there is a fix to export the files through framework 4.5 and do contact us if you need further details, we shall discuss on the same. Thank you for your support. Request you to email @
    [email protected]/[email protected]
    Candida

    Presumably you're using Safari?
    You can change that in Safari Preferences (at least in 5.0.3, might be different in 5.1.x)
    The checkbox at the bottom will do that for you. However! I strongly advise against permitting that; there have been, and no doubt will be again, malware that uses that to bypass authentication.
    Just select Desktop as the default download location so you don't have to dig for the files.

  • How to set password for a zip file and should be checked when reading that

    Hi friends,
    how to set password for a zip file and should be checked when reading that file???
    thanks.
    Praveen Reddy.J

    Heyy man, i think, u did not get my problem.
    all i have to do is:
    i have to create a zip file, and we should secure it with password when creating. and whenever the user wants to open that zip file he should provide correct passowrd otherwise he could not read that file. So, we should check for that also.
    Tanks for reply.

  • Read encrpted zip file and ftp unzip file

    Hi,
    I have a situation,where i need to read 3 zip files, which are encrpted, and each zip file may have lot of images and text files. all i want to do is, read these 3 zip files and unzip + ftp to another directory. No mapping is involved. if the three files are not there, it should error out.
    I have some ideas, but thought if any of you have better ideas.
    Thanks
    Pandari

    Hi Pandari
    File adapter
    module to zip and unzip
    /people/stefan.grube/blog/2007/02/20/working-with-the-payloadzipbean-module-of-the-xi-adapter-framework
    /people/michal.krawczyk2/blog/2007/02/08/xipi-command-line-sample-functions
    <b>Check this weblog:</b>
    /people/stefan.grube/blog/2007/02/20/working-with-the-payloadzipbean-module-of-the-xi-adapter-framework
    Check this out !
    /people/stefan.grube/blog/2007/02/20/working-with-the-payloadzipbean-module-of-the-xi-adapter-framework%3Fpage%3Dlast%26x-order%3Ddate%26x-showcontent%3Doff
    also
    https://service.sap.com/sap/support/notes/965256
    Check this weblog on how to zip the file using XI:
    /people/stefan.grube/blog/2007/02/20/working-with-the-payloadzipbean-module-of-the-xi-adapter-framework
    PayloadZip Bean
    /people/stefan.grube/blog/2007/02/20/working-with-the-payloadzipbean-module-of-the-xi-adapter-framework%3Fpage%3Dlast%26x-order%3Ddate%26x-showcontent%3Doff
    Through command line
    Check case 2 in this blog
    /people/michal.krawczyk2/blog/2007/02/08/xipi-command-line-sample-functions
    or ref plsz go tru it,
    /people/michal.krawczyk2/blog/2007/02/08/xipi-command-line-sample-functions
    Check this weblog on this from stefan:
    /people/stefan.grube/blog/2007/02/20/working-with-the-payloadzipbean-module-of-the-xi-adapter-framework
    http://help.sap.com/saphelp_nw70/helpdata/en/84/2e3842cd38f83ae10000000a1550b0/frameset.htm
    /people/michal.krawczyk2/blog/2005/12/18/xi-sender-mail-adapter--payloadswapbean--step-by-step
    Zip or Unzip your Payload with the new PayloadZipBean module of the XI Adapter
    /people/stefan.grube/blog/2007/02/20/working-with-the-payloadzipbean-module-of-the-xi-adapter-framework
    XI/PI: Command line sample functions -> go through case 2
    /people/michal.krawczyk2/blog/2007/02/08/xipi-command-line-sample-functions
    Create encrypted ZIP files
    Thanks!!!

  • Reading a file and changing one part of the file

    I am trying to read a file and then I want to change the first value on each line. The file I am reading is a .HEADER file. Which is just read in notepad I am just opening this like a txt file. I get no say at all how this file is created originally
    I want to change the value on the first line the a new title plus the ext .dat. The file is below. This stays the same format just with different values.
    ECG000 1 171 26112 9:14:56 23/04/2002
    ECG000 8 43(0) 8 127 79 -24066 0 AED trace
    I want to change the ECG000 to a new value eg Pat1.dat on the first line and Pat1 on the second line. When I read this file in and output to the dos window I get ECG000 0 0 0 and that is it. Any ideas why this is happening and how I can replace the values in the file??
         private void FileExt() throws IOException
              System.out.println("In function");
              BufferedReader br = new BufferedReader(new FileReader("c:\\Projects\\FirstSupport\\ECG000.HEADER"));
              String s;
              Vector data = new Vector();
              ECGFile = new FileWriter("c:\\Projects\\FirstSupport\\ECG.txt",true);
              System.out.println("Reading the file");
              while ((s = br.readLine()) != null)
              data.add(s);
              System.out.println(s);
              System.out.println("Finished");
              String label = s.substring(0, s.indexOf(" "));
              System.out.println(label);
              String newLabel = (label+".dat");
              System.out.println(newLabel);
         }

    I think this is what you're looking for:     private void FileExt() {
              java.util.List data=new ArrayList();
              String s;
              try {
                   BufferedReader br=new BufferedReader(new InputStreamReader(
                        new FileInputStream(new File("ECG000.HEADER"))));
                   while ((s = br.readLine()) != null)  {
                        data.add(s);
                        System.out.println(s);
                   br.close();
              catch (FileNotFoundException fnfe) {
                   System.out.println("Input file not found");
                   return;
              catch (IOException ioe) {
                   ioe.printStackTrace();
                   return;
              ListIterator li=data.listIterator();
              try {
                   PrintWriter ECGFile=new PrintWriter(new FileOutputStream(
                        new File("ECG.txt")));
                   while(li.hasNext()) {
                        s=(String)li.next();
                        if (s.substring(0, 6).equals("ECG000")) {
                             s="Pat1.dat"+s.substring(6, s.length());
                        ECGFile.println(s);
                   ECGFile.close();
              catch (FileNotFoundException fnfe1) {}
         }Mark

  • Is there a way to open a zip file received via email on the iPad? I tried and a message popped up saying mail cannot open the attachment.

    Is there a way to open a zip file received via email on the iPad? I tried and a message popped up saying mail cannot open the attachment.

    You need a third party app. Take a look at some of these on this Google page.
    Open zip files on iPad

  • Adobe reader XI crash and hangs when open the pdf file

    After update the adobe reader xi 11.0.10, the reader always crashes and hangs when open the pdf file. Please help me how to do.

    Ben Leung wrote:
    HThis situation is started after I clear the pop up advertisement.
    What kind of advertisement?  In Adobe Reader?  Can you post a screenshot of that: https://forums.adobe.com/thread/1070933
    Regarding the crash, can you try disabling Protected Mode through the registry: download, unzip, then run the registry script https://files.acrobat.com/a/preview/49eeb48b-07c5-4502-984c-8a25259914fa

  • How to read file and output base64 string?

    im having a hard time reading binary file and converting it to base64.
    is there a parameter in extendscript like file.read('base64') ??

    It is possible in HTML:
    var path = "/tmp/test"; 
    result = window.cep.fs.readFile(path, cep.encoding.Base64);
    if (0 == result.err) {
         //success
         var base64Data = result.data;
         var data = cep.encoding.convertion.b64_to_utf8(base64Data);
    else {
         ...// fail
    You can also refer to the following samples for more examples:
    https://github.com/Adobe-CEP/Samples/tree/master/Flickr
    https://github.com/Adobe-CEP/Samples/tree/master/Collage

Maybe you are looking for

  • JMS Correlation Issue

    Hello I actually stole some of the text of this question from a previous post. The post hasn't had any activity for over a month, so I thought I would repost as I need a solution. I have modified it to my situation. I need to implement following scen

  • IPod G1 froze up after trying to update.

    Giving me the error 1604.  Have tried reloading itunes.  Will not let me restore--and gives me error 5002 when trying to download software update from apple.

  • How do I edit my alias and name in the new "My Settings" ?

    How do I edit my alias (and/or name) in the new "My Settings" panel ? The alias and name are not editable. When using myinfo.apple.com, there is no "alias" field. This seems to be only a feature in Discussions but is no more editable. Please help !

  • How to configure PI user in organization plan?

    Hello SRM guys, When transfer external purchase requirement from ECC to SRM, PI user is needed assigned to organization plan. My question is: Which role should be assigned to PI user.  Which attribute should be configred in organization plan. Any one

  • Hello....unable to install flash player on internet explorer 10

    please provide assistance to installing flash player on internet explorer 10... message states please close the following program... internet explorer (installation stop at 50%.