Vik
Vik

Reputation: 9289

Scanner and Multithreading issues?

I have following code to read entire file data:

calling method(String zipFile){
            ZipInputStream zis =
                new ZipInputStream(new FileInputStream(zipFile));
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();
            while (ze != null) {
                String fileName = ze.getName();

            File newFile =
                new File(Constants.OUTPUT_FOLDER + File.separator +
                         fileName);

            if (ze.isDirectory()) {
                new File(newFile.getParent()).mkdirs();
            } else {
                new File(newFile.getParent()).mkdirs();
                            createBlobDomain(zFile,ze);

                }
            }
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();
}


public String method(ZipFile zf, ZipEntry ze){
scan = new Scanner(zf.getInputStream(ze));
if(scan.hasNext())
    fullText = scan.useDelimiter("\\A").next();
return fullText;
}

Please ignore it from compilation perspective as i removed some code not really relevant here. It works fine when run from the webapp as a single instance. But it i run it from two different browsers at the same time then i hit below exception. Please advise what could be going wrong and how to fix it.

java.util.InputMismatchException
  at java.util.Scanner.throwFor(Scanner.java:840)
  at java.util.Scanner.next(Scanner.java:1347)

Upvotes: 1

Views: 141

Answers (2)

fge
fge

Reputation: 121720

It looks to me that what you want to do is to copy the contents of a zip into a given folder.

Provided you use Java 7+, it's actually pretty simple to do that; this code uses java7-fs-more to help you do the job:

public static void extractZip(final String zipfile, final String dstdir)
    throws IOException
{
    final Map<String, ?> env = Collections.singletonMap("readonly", "true);
    final Path path = Paths.get(zipfile);
    final URI uri = URI.create("jar:" + path.toUri());

    try (
        final FileSystem zipfs = FileSystems.newFileSystem(uri, env);
    ) {
        MoreFiles.copyRecursive(zipfs.getPath("/"), Paths.get(dstdir),
            RecursionMode.FAIL_FAST);
    }
}

Upvotes: 0

shikjohari
shikjohari

Reputation: 2288

I believe the line scan = new Scanner(zf.getInputStream(ze)); is creating the problem. What I understand from you code is scan is an instance variable which you are assigning a new Scanner with every thread. I would suggest to make it as a local variable in your method. Correct me If I misunderstood anything.

Scanner scan = new Scanner(zf.getInputStream(ze))

Upvotes: 3

Related Questions