Milesh
Milesh

Reputation: 271

Converting inputStream from a ZipFile to String

Here the main functionality of my web application is to upload .zip file and store it at the server side but before doing that I need to do some following task: 1.) .zip file contains the xml file, I have to first validate the xml file using schema. 2.) if the xml file is valid than I need to convert the content of the xml file into string without unzipping the file i.e. from the inputstream.

I am successfull in validating the xml file but I am getting the following exception while converting the string from the inputstream: "java.io.EOFException: Unexpected end of ZLIB input stream"

I have tried all the solutions provided in the Stack Overflow and other forum site but I am not yet successfull. Any help will be really appreciated:

Following is the code:

try
    {
        ZipFile zipFileUtil = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> zipFileContents = zipFileUtil.entries();
        while(zipFileContents.hasMoreElements())
        {

            ZipEntry zipEntry = zipFileContents.nextElement();
            if(zipEntry.getName().equals("File.xml"))
            {
                InputStream sourceFile = zipFileUtil.getInputStream(zipEntry);
                if(isValidAsPerXSD(sourceFile))
                {
                    //At this line Exception is Generated
                    String xmlContent = IOUtils.toString(sourceFile);
                }
            }
        }

    }
    catch(Throwable t)
    {
        System.out.println("Exception: "+t.getMessage());
    }

Upvotes: 3

Views: 6999

Answers (1)

Lotfi
Lotfi

Reputation: 1205

You cannot read the stream "sourceFile" twice ! An input stream is supposed to be read sequentially to the end. You must close it and reopen it.

InputStream sourceFile = zipFileUtil.getInputStream(zipEntry);
if(isValidAsPerXSD(sourceFile))
{
    sourceFile.close();
    sourceFile = zipFileUtil.getInputStream(zipEntry);
    //At this line Exception is Generated
    String xmlContent = IOUtils.toString(sourceFile);
}
sourceFile.close();

Upvotes: 2

Related Questions