Apache-zip.jar name attachment file bad encoding

I have following code. which create zip archive, but name attachment files bad encoding.
name attachment files in encoding UTF-8. letters of Russian alphabet -"имя.txt". get - "¯à¨ï⨥  à鸞.txt" OS - Ubuntu 9.10 64-b
package action;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import java.io.*;
import java.util.Arrays;
import java.util.List;
public class CreateArchive {
    private byte[] getByteFromFile(String file) throws IOException {
        InputStream is = new FileInputStream(file);
        long length = file.length();
        if (length > Integer.MAX_VALUE) {
            throw new IOException("Size file bad: "+file);
        byte[] bytes = new byte[(int)length];
        int offset = 0;
        int numRead;
        while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file);
        is.close();
        return bytes;
    public void createZip(OutputStream outputStream, List<String> files) {
        byte[] buf = new byte[1024];
        try {
            ZipOutputStream out = new ZipOutputStream(outputStream);
            out.setEncoding("UTF-8");
            for (String fileName: files) {
                ByteArrayInputStream sourceStream = new ByteArrayInputStream(getByteFromFile(fileName));
                out.putNextEntry(new ZipEntry(fileName));
                int len;
                while ((len = sourceStream.read(buf)) != -1) {
                    out.write(buf, 0, len);
                out.closeEntry();
            out.close();
        } catch (IOException e) {
            System.out.print(e);
    public static void main(String[] args) throws IOException {
        CreateArchive files = new CreateArchive();
        OutputStream outputStream = new FileOutputStream("file.zip");
        files.createZip(outputStream, Arrays.asList("&#1080;&#1084;&#1103;.txt"));
        outputStream.close();
}Sorry for me bad english
Edited by: P1tBull on Mar 24, 2010 5:35 AM

Real task was create general archive is selected users files and transmission he in one stream
package action;
import org.apache.tools.zip.ZipEntry;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipOutputStream;
public class StreamFiles extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        OutputStream out = response.getOutputStream();
        try {
            response.setContentType("'application/zip'; charset='UTF-8'");
            response.setContentType("name=AllFile");
            response.setHeader("Content-disposition", "attachment; filename*=utf-8" + "''" + java.net.URLEncoder.encode("AllFile.zip", "UTF-8") + ";");
            if (request.getHeader("user-agent") != null) {
                if (request.getHeader("user-agent").indexOf("Safari") != -1) {
                    response.setHeader("Content-Disposition", "attachment");
                    response.setContentType("application/octet-stream");
                } else if (request.getHeader("user-agent").indexOf("MSIE") != -1 || request.getHeader("user-agent").indexOf("Chrome") != -1) {
                    response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode("AllFile.zip", "UTF-8"));
            List<String> files = Arrays.asList("catalina.bat", "startup.sh", "version.sh", "tomcat-juli.jar");
            createZip(out, files);
        } catch (Exception ex) {
            request.setAttribute("javax.servlet.jsp.jspException", ex);
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/error.jsp");
            requestDispatcher.forward(request, response);
        } finally {
            out.flush();
            out.close();
    private byte[] getByteFromFile(String file) throws IOException {
        InputStream is = new FileInputStream(file);
        long length = file.length();
        if (length > Integer.MAX_VALUE) {
        byte[] bytes = new byte[(int)length];
        int offset = 0;
        int numRead;
        while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file);
        is.close();
        return bytes;
    public void createZip(OutputStream outputStream, List<String> files) {
        byte[] buf = new byte[1024];
        try {
            ZipOutputStream out = new ZipOutputStream(outputStream);
            for (String fileName: files) {
                ByteArrayInputStream sourceStream = new ByteArrayInputStream(getByteFromFile(fileName));
                out.putNextEntry(new ZipEntry(fileName));
                int len;
                while ((len = sourceStream.read(buf)) != -1) {
                    out.write(buf, 0, len);
                out.closeEntry();
            out.close();
        } catch (IOException e) {
            System.out.print(e);
}but mistake on real host don't repeated, so thanks for answer
Edited by: P1tBull on Mar 24, 2010 8:14 AM

Similar Messages

  • Zip.ZipInputStream cannot extract files with Chinese chars in name

    Dear friends,
    Peace b upon u!
    I am trying to read a zip file (~3000 files)containing one
    or more files with Chinese, Japanese or Korean names, the
    getNextEntry method throws an IllegalArgumentException as below after extracting just ~300 files as below:-
    java.lang.IllegalArgumentException
            at java.util.zip.ZipInputStream.getUTF8String(Unknown Source)
            at java.util.zip.ZipInputStream.readLOC(Unknown Source)
            at java.util.zip.ZipInputStream.getNextEntry(Unknown Source)
            at testZipFiles.getZipFiles(testZipFiles.java:65)
            at testZipFiles.main(testZipFiles.java:18) issue:java.util.zip.ZipInputStream cannot extract files with Chinese chars in name
    Category java:classes_util_jarzip
    Plz let me know 1 of the ways which I can solve this issue.
    1)if someone has JAVA DCOMPILER plz send the SOURCE Code
    for the ZipInputStream.class to me..I need to edit it using 1 of the solutions as provided below which I googled.
    2)If there is an alternate or upgraded java.util.zip.ZipInputStream or any org.apache.tools.zip.* package which can read such files..If yes where I can download the same on net.
    3)Any other easier solution, which can let me extract all files (by excluding Chinese files thru CATCH) without the extractor process to fail altogether.
    On net I found that the only solution with this is:-
    - edit the new ZipEntry, remove the static initializer that calls
    the native methods initIDs().
    this step seems a bit scary, but it's according to the
    workaround
    to bug #4244499 (the workaround of Olive64, THU JUN 05
    01:55 P.M. 2003),
    that handles a similar bug at the ZipOutputStream.
    Now you have a ZipInputStream that supports multi-bytes
    entry names.
    to extract the zip file, using the fixed code that is offered
    above,
    create a function that gets an "encoding" string, a "destPath"
    string
    and a "sourceFile" (zipped) and does :
    ZipInputStream zipinputstream = null;
    ZipEntry zipentry;
    zipinputstream = new ZipInputStream(new FileInputStream
    (sourceFile),encoding);
    zipentry = zipinputstream.getNextEntry();
    while (zipentry != null) { //for each entry to be extracted
        String entryName = zipentry.getName();
        int n;
        FileOutputStream fileoutputstream = new FileOutputStream
    ( destPath + entryName );
        while ((n = zipinputstream.read(buf, 0, 1024)) > -1)
            fileoutputstream.write(buf, 0, n);
        fileoutputstream.close();
        zipinputstream.closeEntry();
        zipentry = zipinputstream.getNextEntry();
    }//while
    zipinputstream.close();

    Hi friend,
    We'd better to ask one question in each thread. If you have another issue, you can consider to open up a new thread in this forum.
    Now for the first question, do you mean this picture? It throws access exception in archive2.
    If so , because your extractPath is a path, not a directory.You should add +"xxx.zip". For more information, please refer to
    ZipFile.Open
    Method (String, ZipArchiveMode).
    For the second question, you can use the following code to skip the error message.
    while (true)
    try
    //do something;
    catch (Exception ex)
    { continue; }
    Good day!
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Attachment - File name with accents

    Hello,
    I finally realized why Mail was sending weird name attachements (.doc00, .doc\ca, etc.). It happens when a file name contains an accent (é, à, è...). Now, I'm French, so accents are very useful...
    I mean, why is this happening now? Is Mac OS becoming like Windows NT or 98?
    Any fixes in sight? Any solutions?
    Thanks,
    Daniel
    P.-S. : Tried 10.5.3, not better, plus the upgrade crashed my IBook G4 two times! Way to go, Apple!

    When I use Thunderbird/gmail to send my email, and the attachment with non-ASCII file name can be read correctly using the following codes:
    String attFileName = MimeUtility.decodeText(part.getFileName());
    but when I send the email use outlook2003, it just return bad file name.
    The following is the attachment related content:
    Thunderbird:
    --------------090808030807020200030902
    Content-Type: text/plain;
    name="=?GB2312?B?ztK1xLzGy+MudHh0?="
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment;
    filename*=GB2312''%CE%D2%B5%C4%BC%C6%CB%E3%2E%74%78%74
    OUTLOOK:
    ------_=_NextPart_001_01CACBCD.3577323E
    Content-Type: text/plain;
    name="=?gb2312?B?ztK1xLzGy+MudHh0?="
    Content-Transfer-Encoding: base64
    Content-Description: =?gb2312?B?ztK1xLzGy+MudHh0?=
    Content-Disposition: attachment;
    filename="=?gb2312?B?ztK1xLzGy+MudHh0?="
    GMAIL:
    --000e0cd11976ac6e63048297dd06
    Content-Type: text/plain; name="=?GB2312?B?ztK1xLzGy+MudHh0?="
    Content-Disposition: attachment; filename="=?GB2312?B?ztK1xLzGy+MudHh0?="
    Content-Transfer-Encoding: base64
    X-Attachment-Id: f_g770st560
    What is the difference?

  • Decode attachment file name RFC 2231

    Hello,
    according to the [RFC 2231|http://tools.ietf.org/html/rfc2231] , the headers are encoded to something like
    From: =?US-ASCII*EN?Q?Keith_Moore?= <[email protected]>
    How can decode such a string, in Java ? I've found only [this implementation|http://svn.apache.org/repos/asf/geronimo/specs/tags/geronimo-javamail_1.4_spec-1.5/src/main/java/org/apache/geronimo/mail/util/RFC2231Encoder.java] from Apache Geronimo. Are there other implementations ?
    Thanks,
    T.

    Your subject talks about attachment file names, but your example uses the From header.
    For attachment file names and other parameters, set the property mail.mime.decodeparameters
    to "true". See the javadocs for the javax.mail.internet package for the list of properties you can set.
    Unfortunately, JavaMail doesn't support the specification of a language ("EN") in addition to a charset
    ("US-ASCII") as in your example. That's a bug that I'll need to fix.

  • Apostrophe ( ' ) in the attachment file name

    Hi Guys,
    We have a EP application where the users are allowed to attach files. In the UAT and Prod box, there is apache server where as its not there in development.
    The issue is coming in UAT and production
    The user attached a file with (') in it e.g. SAP's.jpg
    The file was attached but when the user tries to view it, it gets error as
    FORBIDDEN
    you dont have permission to access /irj/go/km/docs/documents/SAP's.jpg
    I tried to use different file names such as  SAP~s.jpg. All seems to work so its not really a special character issue.
    BASIS team is not able to find any setting which could allow this.
    Appreciate if you can provide some explaination or the list of character which are not allowed.
    Thanks,
    Shailesh

    It seems (') is not allowed due to security reasons thus has a special meaning so not allowed

  • Names of files with names in national encoding

    Hello.
    I have created the downloading of files following the example, which oracle gives (http://download.oracle.com/docs/cd/E14373_01/appdev.32/e13363/up_dn_files.htm#CJAHDJDA - Create Download Page for Embedded PL/SQL Gateway).
    The name of file in DB stored in russian in utf-8, encoding of page is also utf-8. But when I click to download file, browser shows me in the save as window the name of file in incorrect encoding (for example the name Название таблиц.doc"(russian) shown me as "!_740=85 B01;8F.doc")
    Can anyone help?
    Apex 3.2/Glassfish
    Thanks.

    Maybe there is a problem in http header in my function
    create or replace PROCEDURE "DOWNLOAD_COMPETITOR_FILE" (p_file in number) AS
    v_mime VARCHAR2(400);
    v_length NUMBER;
    v_file_name VARCHAR2(2000);
    Lob_loc BLOB;
    BEGIN
    SELECT d.COMPETITOR_file_mimetype, d.COMPETITOR_file_file, d.COMPETITOR_file_filename
    ,DBMS_LOB.GETLENGTH(d.COMPETITOR_file_file)
    INTO v_mime,lob_loc,v_file_name,v_length
    FROM COMPETITOR_file d
    WHERE d.COMPETITOR_file_id = p_file;
    -- set up HTTP header
    -- use an NVL around the mime type and
    -- if it is a null set it to application/octect
    -- application/octect may launch a download window from windows
    owa_util.mime_header( nvl(v_mime,'application/octet'), FALSE );
    -- set the size so the browser knows how much to download
    htp.p('Content-length: ' || v_length);
    -- the filename will be used by the browser if the users does a save as
    htp.p('Content-Disposition: attachment; filename="'||replace(replace(substr(v_file_name,instr(v_file_name,'/')+1),chr(10),null),chr(13),null)|| '"');
    -- close the headers
    owa_util.http_header_close;
    -- download the BLOB
    wpg_docload.download_file( Lob_loc );
    end download_COMPETITOR_file;
    ?

  • JavaMail with non-ascii file name attachment.

    Hello,
    I add a file to the mail, which file name is a Chinese name. After I sent it and receive in other email client (M$outlook), it could not display the correct file name for the attachment file.
    How can solve this ?

    The MIME standards for non-ASCII filenames are not widely implemented.
    Many mailers use an ad hoc method for encoding filenames. JavaMail
    supports both methods, but you need to set properties, such as the
    mail.mime.encodefilename property. See the JavaMail javadocs for
    the javax.mail.internet package.

  • How to store ZIP & JAR files.

    I am succeeded in storing & then sending big files as an attachment except for ZIP & JAR files.Can anyone guide me what's the problem with ZIP & JAR files

    Hi sachin !!
    I m facing problem in big size attachments ..
    it always give me exception
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 552 Message size exceeds fixed maximum message size
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at MailTest.postMail(MailTest.java:82)
    at MailTest.main(MailTest.java:19)
    Can u tell me how to set the size for large attachments ?
    File size upto 1 mb work fine , but file with 2mb size gives me problem ..
    Plz reply me Fast , waiting :)
    thanx
    Regards
    Khurram

  • Mail adapter - how to dinamically change attachment file name in sending

    How can I dynamically change the attachment filename when preparig email to be sent? The attachment is an invoice in XML format and I have to put the invoice number into the attachment file name.
    Thanks in advance.
    Giuseppe.

    Hi,
    Go through this docs.
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/9e6c7911-0d01-0010-1aa3-8e1bb1551f05
    http://help.sap.com/saphelp_nw04/helpdata/en/6b/4493404f673028e10000000a1550b0/content.htm
    Hope these bloga are useful..
    /people/community.user/blog/2006/09/07/email-reporting
    /people/community.user/blog/2006/09/08/email-report-as-attachment-excelword
    /people/michal.krawczyk2/blog/2005/12/18/xi-sender-mail-adapter--payloadswapbean--step-by-step
    /people/prasad.ulagappan2/blog/2005/06/07/mail-adapter-scenarios-150-sap-exchange-infrastructure
    /people/michal.krawczyk2/blog/2005/03/07/mail-adapter-xi--how-to-implement-dynamic-mail-address
    https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/1685 [original link is broken] [original link is broken] [original link is broken]
    /people/michal.krawczyk2/blog/2005/11/23/xi-html-e-mails-from-the-receiver-mail-adapter
    Thanks,
    Satya

  • When downloading a file, only the first word of the attached file is included in the 'file name' field, not the entire file name, as it used to.

    Regardless of filetype, only the first word of the file is filled into the "Enter name of file to save to..." dialog box. I'm set up to 'save file' in the FF Options > Applications tab for the basic MS and Adobe files. To successfully use/find the downloaded file, I type in the remainder of the file name. Have I overlooked an additional setting? Running FF 18.0 on a Win7 PC.

    Start Firefox in <u>[[Safe Mode|Safe Mode]]</u> to check if one of the extensions (Firefox/Tools > Add-ons > Extensions) or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox/Tools > Add-ons > Appearance).
    *Do NOT click the Reset button on the Safe mode start window or otherwise make changes.
    *https://support.mozilla.org/kb/Safe+Mode
    A possible cause is that the server sends a wrong response header.
    The server may not comply to RFC 5987 and sends a wrong Content-Disposition:attachment; filename header.
    * https://developer.mozilla.org/en/Firefox_8_for_developers#Network

  • Mail adapter- Attachment file name of scheme ddmm

    Hi ,
    I am working on File to Mail scenario.
    I checked on SDN, but I could not find exact solution.
    My requirement is :
    I need to mail HTML report file as attachment.
    To generate attachment file, I have done XSL mapping.
    Attachment file name should be : yyyymmdd.htm
    Mail text should be: This is autogenerated mail, please do not reply.
    Mail subject: SAP XI report ddmmyyy
    Please provide your inputs.
    Best Regards,
    Divyesh

    Hi Henrique,
    Thanks a lot for your response.
    Your answer is very helpful.
    I tried your code.
    I am getting error in RWB:  here I am including audit Log:
    2009-04-02 17:39:41 Success MP: Entering module processor
    2009-04-02 17:39:41 Success MP: Processing local module localejbs/CreateAttachment
    2009-04-02 17:39:41 Success MP: Processing local module localejbs/sap.com/com.sap.aii.adapter.mail.app/XIMailAdapterBean
    2009-04-02 17:39:41 Success Mail: message entering the adapter
    2009-04-02 17:39:41 Success Mail: Receiver adapter entered with qos ExactlyOnceInOrder
    2009-04-02 17:39:41 Success Mail: calling the adpter for processing
    2009-04-02 17:39:42 Error Mail: call failed; java.io.IOException: Missing mandatory element <sap:Manifest><sap:Payload><sap:Name>
    2009-04-02 17:39:42 Success Mail: sending a delivery error ack ...
    2009-04-02 17:39:42 Success Mail: sent a delivery error ack
    2009-04-02 17:39:42 Error MP: Exception caught with cause com.sap.aii.af.ra.ms.api.RecoverableException: java.io.IOException: Missing mandatory element <sap:Manifest><sap:Payload><sap:Name>
    2009-04-02 17:39:42 Error Mail: error occured: com.sap.aii.af.ra.ms.api.RecoverableException: java.io.IOException: Missing mandatory element <sap:Manifest><sap:Payload><sap:Name>
    2009-04-02 17:39:42 Error Exception caught by adapter framework: java.io.IOException: Missing mandatory element <sap:Manifest><sap:Payload><sap:Name>
    2009-04-02 17:39:42 Error Delivery of the message to the application using connection Mail_http://sap.com/xi/XI/System failed, due to: com.sap.aii.af.ra.ms.api.RecoverableException: java.io.IOException: Missing mandatory element <sap:Manifest><sap:Payload><sap:Name>.
    2009-04-02 17:39:42 Success The message status set to WAIT.
    Can you please provide me help on this?
    Best Regards,
    Divyesh

  • Dynamic File Name attachment in Mail Adpater

    Hi All,
    We have Requirement where we need attach file with Dynamic Names in mail adapter PI7.0 .Right now we are using some of the modules to genarate file attachement with hard coded value for name of the file.
    Java beans we are using are
    localejbs/AF_Modules/StrictXml2PlainBean
    localejbs/AF_Modules/MessageTransformBean
    localejbs/AF_Modules/TextCodepageConversionBean
    sap.com/com.sap.aii.adapter.mail.app/XIMailAdapterBean
    Please let us know how we can acheive this.
    Thanks,
    Madhu

    Hi Madhusudhan,
    File attachment with the dynamic name is possible by using the Adapter module as well as without the Adpater module through coding.
    let me know which kind of attachment you want in mail and which is your sending system (like SAP R/3)?
    Thanks & Regards
    Jagesh

  • Mail to File - how to read the attachment file name from the subject.

    I need to use the SHeaderSUBJECT's value in the receiver file adapter's variable substitution.
    This is a Mail to File scenario without design part where the attachment file name comes in the subject of the mail.
    I see the below in the dynamicconfiguration section. How can i retrive the value from dynamicconfiguration section to the filename.
    <SAP:DynamicConfiguration xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">
    <SAP:Record namespace="http://sap.com/xi/XI/System/Mail" name="SHeaderSUBJECT">PlainAttachment.txt</SAP:Record>
    </SAP:DynamicConfiguration>
    Points will be rewarded.

    Try to use sthg like this in a UDF :
    DynamicConfiguration conf = (DynamicConfiguration) container.getTransformationParameters().getStreamTransformationConstants.DYNAMIC_CONFIGURATION);
    DynamicConfigurationKey key = DynamicConfigurationKey.create(“http://sap.com/xi/XI/System/Mail”,“SHeaderSUBJECT”);
    String value = conf.get(key);
    or in a JAVA mapping :
    DynamicConfiguration dynConf = (DynamicConfiguration) param.get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
    DynamicConfigurationKey dynKey = DynamicConfigurationKey.create((“http://sap.com/xi/XI/System/Mail”,“SHeaderSUBJECT”);
    String keyValue = dynConf.get(dynKey);
    param is the map object from the execute() method of your mapping ...
    Hope this helps
    Chris
    Edited by: Christophe PFERTZEL on Apr 23, 2008 11:34 AM

  • The name of File when Saving New Keynote has "~" attached at the end

    When I do a save file in Keynote, the name of file has "~" attached at the end. It creates a new file so now I have two files which look like this:
    StolbaCh22.key
    StolbaCh22~.key
    Why is this happening? What am I doing wrong - can I delete either one of these?

    Have you nominated in Preferences to have a backup version every time you save?
    Or this maybe be a temporary file whilst you are working on the original.
    If they are both on your desktop without Keynote being open, you could safely assi=ume the one with the most recent time/date is the last one you worked on.
    Peter

  • Mail attachment file name changes

    when i send mail with attached file having english file name, mail receiver can receive it as correct file name.
    But if having korean file name(ex: 우리나라.doc), recipient receives it as different file name(ie 우리나라.라.doc).
    how can i solve this problem?

    Is the reciever using windows? If so you can choose Edit > Attachments > Always Send Windows Friendly Attachments.

Maybe you are looking for