Problem unzipping larger files with Java

When I extract small zip files with java it works fine. If I extract large zip files I get errors. Can anyone help me out please?
import java.io.*;
import java.util.*;
import java.net.*;
import java.util.zip.*;
public class  updategrabtest
     public static String filename = "";
     //public static String filesave = "";
    public static boolean DLtest = false, DBtest = false;
     // update
     public static void main(String[] args)
          System.out.println("Downloading small zip");
          download("small.zip"); // a few k
          System.out.println("Extracting small zip");
          extract("small.zip");
          System.out.println("Downloading large zip");
          download("large.zip"); // 1 meg
          System.out.println("Extracting large zip");
          extract("large.zip");
          System.out.println("Finished.");
          // update database
          boolean maindb = false; //database wasnt updated
     // download
     public static void download (String filesave)
          try
               java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
               java.net.URL("http://saveourmacs.com/update/" + filesave).openStream());
               java.io.FileOutputStream fos = new java.io.FileOutputStream(filesave);
               java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
               byte data[] = new byte[1024];
               while(in.read(data,0,1024)>=0)
                    bout.write(data);
               bout.close();
               in.close();
          catch (Exception e)
               System.out.println ("Error writing to file");
               //System.exit(-1);
     // extract
     public static void extract(String filez)
          filename = filez;
        try
            updategrab list = new updategrab( );
            list.getZipFiles();
        catch (Exception e)
            e.printStackTrace();
     // extract (part 2)
    public static void getZipFiles()
        try
            //String destinationname = ".\\temp\\";
            String destinationname = ".\\";
            byte[] buf = new byte[1024]; //1k
            ZipInputStream zipinputstream = null;
            ZipEntry zipentry;
            zipinputstream = new ZipInputStream(
                new FileInputStream(filename));
            zipentry = zipinputstream.getNextEntry();
               while (zipentry != null)
                //for each entry to be extracted
                String entryName = zipentry.getName();
                System.out.println("entryname "+entryName);
                int n;
                FileOutputStream fileoutputstream;
                File newFile = new File(entryName);
                String directory = newFile.getParent();
                if(directory == null)
                    if(newFile.isDirectory())
                        break;
                fileoutputstream = new FileOutputStream(
                   destinationname+entryName);            
                while ((n = zipinputstream.read(buf, 0, 1024)) > -1)
                    fileoutputstream.write(buf, 0, n);
                fileoutputstream.close();
                zipinputstream.closeEntry();
                zipentry = zipinputstream.getNextEntry();
            }//while
            zipinputstream.close();
        catch (Exception e)
            e.printStackTrace();
}

In addition to the other advice, also change every instance of..
kingryanj wrote:
          catch (Exception e)
               System.out.println ("Error writing to file");
               //System.exit(-1);
..to..
catch (Exception e)
e.printStackTrace();
}I am a big fan of the stacktrace.

Similar Messages

  • Can't create log file with java.util.logging

    Hi,
    I have created a class to create a log file with java.util.logging
    This class works correctly as standalone (without jdev/weblogic)
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.logging.*;
    public class LogDemo
         private static final Logger logger = Logger.getLogger( "Logging" );
         public static void main( String[] args ) throws IOException
             Date date = new Date();
             DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
             String dateStr = dateFormat.format(date);
             String logFileName = dateStr + "SEC" + ".log";
             Handler fh;          
             try
               fh = new FileHandler(logFileName);
               //fh.setFormatter(new XMLFormatter());
               fh.setFormatter(new SimpleFormatter());
               logger.addHandler(fh);
               logger.setLevel(Level.ALL);
               logger.log(Level.INFO, "Initialization log");
               // force a bug
               ((Object)null).toString();
             catch (IOException e)
                  logger.log( Level.WARNING, e.getMessage(), e );
             catch (Exception e)
                  logger.log( Level.WARNING, "Exception", e);
    }But when I use this class...
    import java.io.File;
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.logging.FileHandler;
    import java.util.logging.Handler;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import java.util.logging.XMLFormatter;
    public class TraceUtils
      public static Logger logger = Logger.getLogger("log");
      public static void initLogger(String ApplicationName) {
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(date);
        String logFileName = dateStr + ApplicationName + ".log";
        Handler fh;
        try
          fh = new FileHandler(logFileName);
          fh.setFormatter(new XMLFormatter());
          logger.addHandler(fh);
          logger.setLevel(Level.ALL);
          logger.log(Level.INFO, "Initialization log");
        catch (IOException e)
          System.out.println(e.getMessage());
    }and I call it in a backingBean, I have the message in console but the log file is not created.
    TraceUtils.initLogger("SEC");why?
    Thanks for your help.

    I have uncommented this line in logging.properties and it works.
    # To also add the FileHandler, use the following line instead.
    handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandlerBut I have another problem:
    jdev ignore the parameters of the FileHandler method .
    And it creates a general log file with anothers log files created each time I call the method logp.
    So I play with these parameters
    fh = new FileHandler(logFileName,true);
    fh = new FileHandler(logFileName,0,1,true);
    fh = new FileHandler(logFileName,10000000,1,true);without succes.
    I want only one log file, how to do that?

  • Large file with fstream with WS6U2

    I can't read large file (>2GB) with the stl fstream. Can anyone do this or is this a limitation of WS6U2 fstream classes. I can read large files with low level function C functions

    I thought that WS6U2 meant Forte 6 Update 2. As to more information, the OS is SunOS 5.8, the file system is NFS mounted from an HP-UX 11.00 box and it's largefile enabled. my belief is that fstream does not implement access to large files, but I can't be sure.
    Anyway, I'm not sure by what you mean by the access to the OS support for largefiles by the compiler, but as I mentioned before, I can read more then 2GB with open() and read(). My problem is with fstream. My belief is that fstream must be largefile enabled. Any idea?

  • I can't open or save file with Java Web Start

    Hi,
    i can't open or save file with Java Web Start:
    import java.io.*;
    import java.util.*;
    public class MetaDataFileCreator {
    public String fileNameSpace = null;
    public String fileName = null;
    protected Properties file = null;
    public MetaDataFileCreator(String fileNameSpace, String fileName) {
    this.fileNameSpace = fileNameSpace;
    this.fileName = fileName;
    public void createMetaDataFile() {
    try {
    System.out.println("file METADATA");
    ClassLoader cl = this.getClass().getClassLoader();
    String nameFileMetaData = fileNameSpace + fileName + ".txt";
    FileOutputStream fileOS = new FileOutputStream(cl.getResource(nameFileMetaData).getFile());
    file = new Properties();
    file.setProperty("aaaaa", "aaaa");
    file.store(fileOS, "");
    fileOS.close();
    } catch (Exception e) {
    System.out.println("Error writing metadata-file: " + e);
    System.exit(1);
    e.printStackTrace();
    I have try also to open a file like this:
    ClassLoader cl = this.getClass().getClassLoader();
    file.load(cl.getResourceAsStream(nameFile));
    also like this:
    try {
    fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
    fss = (FileSaveService)ServiceManager.lookup("javax.jnlp.FileSaveService");
    } catch (UnavailableServiceException e) {
    fss = null;
    fos = null;
    System.out.println("Error with JNLP");
    System.exit(1);
    if (fss != null && fos != null) {
    try {
    // get a FileContents object to work with from the
    // FileOpenService
    FileContents fc = fos.openFileDialog(null, null);
    //FileContents newfc2 = fss.saveAsFileDialog(null, null, fc);
    // get the OutputStream and write the file back out
    if (fc.canWrite()) {
    // don't append
    os = fc.getOutputStream(false);
    } catch (Exception e) {
    e.printStackTrace();
    also like this:
    File f = new File((System.getProperty("user.home")+"x.txt").toString());
    FileOutputStream fileX = new FileOutputStream(f);
    OutputX = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fileX, "UTF8")));
    OutputX.println(....
    but it doesn't work with Java Web Start.
    Can someone help me?
    How can I open or save file?
    thank you.
    Sebastiano

    Did you specify <all-permissions/> in your JNLP file? Did you sign your code? What error are you getting?

  • How to use parameter file with java

    Is it possible to use a parameter file with Java, and is there any class/method to make it easy to call and use these parameter from a text file, other than scanning the whole text file manually as we can do normally with visual basic/c++, so we can call the program with the parameter file, like java testing c:\\testing.ini

    If I understand you correctly, you may be looking for a properties file. This is basically a text file that contains pairs of strings in the form:
    parameter1=value1
    parameter2=value2
    parameter3=value3
    ...etc.
    and the values are retrieved using the java.util.Properties class - see:
    http://java.sun.com/j2se/1.3/docs/api/java/util/Properties.html
    Sample use://Call chis method once, to load the props file.
    //props file is called "demo.properties", and is
    //in a directory that is included in the classpath
        private void loadMyProperties() throws Exception
         InputStream stream = getResourceAsStream("/demo.properties");
         if(stream == null)
             throw new Exception("stream is null!");
         demoProperties = new Properties();
         demoProperties.load(stream);
         stream.close();
    // Then you can retrieve properties in your code using:
    String param3 = demoProperties.getProperty("parameter3");
    //...etc

  • How to check & unzip zip file using java

    Dear friends
    How to check & unzip zip file using java, I have some files which are pkzip or some other zip I want to find out the type of ZIp & then I want to unzip these files, pls guide me
    thanks

    How to check & unzip zip file using java, I have
    ve some files which are pkzip or some other zip I
    want to find out the type of ZIp & then I want to
    unzip these files, pls guide meWhat do you mean "other zip"? Either they're zip archives or not, there are no different types.

  • Problem opening PDF files with adobe

    I cannot get adobe to open my pdf files. Not from internet nor from desktop.
    I downloads fine,. I have installed and reinstalled several times.
    If I try to open it looks like it opens but closes immediately. I tried to open adobe, but nothing. A grey screen and that's it. I cannot access the help button

    Yes, I finally got it working using number 2:-) Thank you very much
    2013/8/1 Pat Willener <[email protected]>
       Re: Problem opening PDF files with adobe  created by Pat Willener<http://forums.adobe.com/people/pwillener>in
    Adobe Reader - View the full discussion<http://forums.adobe.com/message/5557146#5557146

  • Executing a file with Java?

    Hi,
    I wanted to know how I could execute a file with java. Here are a couple scenarios - let's say I am developing an anti-spyware utility and I wanted to first write a batch file, and then create it in a folder, then run it when they click "Run". Then afterwards I want to shutdown their computer.
    My Mindset:
    - FileWriter to create the .bat and write the Batch commands.
    - Execute the batch file.
    - Execute the shutdown.exe file to reboot their PC.
    So my simple question is, how can I execute a file?
    Thanks!
    -Josh

    Well here is the code I have:
                try
                    Runtime.getRuntime().exec("cmd.exe /c test.bat");
                catch(IOException e1)
                    //NOTHING
                }Now my cmd.exe is obviously in my Windows System32 folder, and my "test.bat" file is in my C:\ root directory. So I am wondering why that wont execute. I tried a fer other things too like:
    Runtime.getRuntime().exec("cmd.exe  c:\test.bat");that didn't work either, because you can't have a "\" in a string...
    So how can I get this thing to execute the batch file?

  • Is it possible to play .rm and .wma file with java?

    Hello Friends,
    Please tell me,
    how to play .rm and .wma file with java?
    Thanks,
    Harsh Modha

    As far as I know, you can not play those files.
    Here you have the complete list of supported formats. Hope this helps.
    http://java.sun.com/products/java-media/jmf/2.1.1/formats.html
    Maybe you should try to convert from wma or rm to a supported format before attempting to play it.

  • A Problem about zip a Chinese File with Java Zip package

    Hi,
    my problem is following:
    I use "Java(1.3.1_02) Zip package" to compress some files into a zip File
    all thing is smooth except one:(
    If there is a fileName with Chinese (big5 encoding) characters
    it doesen't work!
    Can anyone tell me how to do?
    Thanks a lot!

    Hi !
    i do have a problem relating with the different character(korean).Hope u must be working with chinese characters.My problem is while displaying the korean characters from database , the characters are broken and not able to display on jsp pages.....
    Hope u can understand my problem.....
    Thanks....

  • Problems running bat file with calls to java programs (.jar)

    I created a bat file with calls to jar programs. In each line,
    I put a call to the programs with parameters, but bat only
    executes the first line and ends execution.
    All lines of my bat file must be executed.
    What should I do?
    Best Regards,
    Pedro Felipe
    [http://pedrofao.blogspot.com|http://pedrofao.blogspot.com]
    [http://viajantesmundo.blogspot.com/|http://viajantesmundo.blogspot.com/]

    user8730639 wrote:
    I realized that the problem isn`t my bat file. I made tests calling another jar files and then all the lines of the batch file were executed. So, the jar file called on my previous bat is finnishing the execution. I verified and the jar apps worked without error.
    I would like to know if exists any command in Java that can cause this effect (close a batch), to modify the open source code of the application.Not that I know of.
    Is prism a bat file?
    If you are invoking bat files from your bat file without using call that would explain it
    :: mymain.bat file
    :: call the first bat file
    call prism.bat arg1 arg2 arg3
    :: call the other bat file
    call prism.bat arg4 arg5 arg6
    ::

  • Loading large files in Java Swing GUI

    Hello Everyone!
    I am trying to load large files(more then 70 MB of xml text) in a Java Swing GUI. I tried several approaches,
    1)Byte based loading whith a loop similar to
    pane.setText("");
                 InputStream file_reader = new BufferedInputStream(new FileInputStream
                           (file));
                 int BUFFER_SIZE = 4096;
                 byte[] buffer = new byte[BUFFER_SIZE];
                 int bytesRead;
                 String line;
                 while ((bytesRead = file_reader.read(buffer, 0, BUFFER_SIZE)) != -1)
                      line = new String(buffer, 0, bytesRead);
                      pane.append(line);
                 }But this is gives me unacceptable response times for large files and runs out of Java Heap memory.
    2) I read in several places that I could load only small chunks of the file at a time and when the user scrolls upwards or downwards the next/previous chunk is loaded , to achieve this I am guessing extensive manipulation for the ScrollBar in the JScrollPane will be needed or adding an external JScrollBar perhaps? Can anyone provide sample code for that approach? (Putting in mind that I am writting code for an editor so I will be needing to interact via clicks and mouse wheel roatation and keyboard buttons and so on...)
    If anyone can help me, post sample code or point me to useful links that deal with this issue or with writting code for editors in general I would be very grateful.
    Thank you in advance.

    Hi,
    I'm replying to your question from another thread.
    To handle large files I used the new IO libary. I'm trying to remember off the top of my head but the classes involved were the RandomAccessFile, FileChannel and MappedByteBuffer. The MappedByteBuffer was the best way for me to read and write to the file.
    When opening the file I had to scan through the contents of the file using a swing worker thread and progress monitor. Whilst doing this I indexed the file into managable chunks. I also created a cache to further optimise file access.
    In all it worked really well and I was suprised by the performance of the new IO libraries. I remember loading 1GB files and whilst having to wait a few seconds to perform the indexing you wouldn't know that the data for the JList was being retrieved from a file whilst the application was running.
    Good Luck,
    Martin.

  • Problems copying large files to external disks

    I have a lot of media and so multiple USB and network based external hard disks.
    I'm having trouble with two in particular that are recent buys. I initially mounted them via a USB hub onto my Time Capsule, but when I had errors, I've now tried mounting them directly to my MacBook Air - and for comparison directly to a Windows laptop.
    And I'm only having problems when it's a Mac doing the copying (MBA to either USB mounted via Time Capsule or directly USB mounted on the MBA).
    The problem is that the drive appears to behave OK for initial copies - but I'm trying to put a set of old movies (captured from a VCR ages ago that I'd recorded off TV) onto one of the drives and (a) it takes ages to copy and (b) eventually I get a write failure. The specific error message is
    The Finder can't complete the operation because some data in "" can't be written. (Error code -36)
    I"ve tried a whole variety of setups - as I've said via Time Capsule and directly mounted. I also wondered if the file system on the drive would make a difference. Out of the box it was formatted with FAT32 and when that failed I've now reformatted with MacOS file system - which I would have thought would give better compatibility (and I've read that FAT32 has a large file size limit - although I think it's 4GB and while I do have one file at 4.04GB, it's not failing the copy on that file).
    I've also connected the drive (when formatted FAT32) to a Windows laptop and (a) it copies faster and (b) it copies successfully.
    Any suggestions for this? Is there some kind of large file (all are >1GB) copy issue with USB mounted devices in OSX?

    As I mentioned in my original post while the disks were originally formatted FAT32 I reformatted then and changed them to Mac OS Extended (Journaled) so that isn't the issue. I still have the problem with the disks using Apple format.
    I've noticed that if I do the copy in pieces, it seems to work. I.e. if I select the full set of 45GB in one copy and paste operation (dragging and dropping using Finder) it fails part way through.
    But if I copy 3/4 movies at a time going back until I have copied all of them then I can get all of them on the disk.
    It suggests to me it's some kind of issue with copying and pasting a very large amount of data in Snow Leopard?

  • [File] Problem while creating files with long pathnames

    Hello everybody
    I'm trying to create File objects corresponding to physical files. These files have very long pathnames because they are located in directories tree with large depth. So, my pathname conatins a lot of directories plus the name of the file itself.
    It seems, that there is a limitation in the length of the pathname that I pass to the File constructor because files with small pathnames are OK bu the ones with very large pathnames cannot be created.
    I tried the different File constructors (File(String pathname) and File(File parent, String childname)) but it still does not work. Even if the second constructor is a little bit better as it succeeds on files where the first constructor failed. But still, it's not enough.
    Please Help!
    Thank you
    Hugo

    RESOLVED!
    The problem was from the OS itself (Windows XP) which accepts at most 255 characters long path names.

  • Problems reading PDF files with i Pad and Mac with 10.8.3 Mountain Lion OS

    I assume InDesign uses the Acrobat XI resources to generate the exported PDFs.
    I have many 1-7 page articles from which I created PDFs via the export function in ID. They all read OK on PC/Apple/Linux based computers.
    I assembled all of the articles into one 50 page document in ID and again exported the large file as a PDF.
    Several of the articles inside the large document now exhibit problems when viewed on an i Pad or a Mac running OS 10.8.3 (Mountain Lion). PC and Linux do not have this problem.
    The problems are, to quote my subscriber: "each paragraph starts with a 'dollar' sign instead of 'Th'. Later the 'Dollar' symbol changes to ' " '. The same thing happens in the Piston Ring article. This doesn't happen on the original PDF files.
    Opening the files in Acrobat Pro XI to look for differences does not discover anything although I assume the problem is somewhere in the font files.
    Any suggestions?

    I've asked the question about the versions and producers of the PDF reader software he is using. I'll be back when that answer comes in.
    I was afraid that Adobe might not use code identical to Acrobat Pro XI to generate PDFs in InDesign. I may have to 'print' to Acrobat and see if that generates a trouble-free PDF.

Maybe you are looking for

  • VMWare Fusion and Parallels Desktop Benchmark Comparison

    This is a quickie benchmark of VMWare Fusion and Parallels Desktop using Super PI, PC Mark 05, and Passmark. VMWare Fusion 36932 Parallels Desktop 3094 Beta 2 Notes: Both virtual machines were allocated with large 10+ GB virtual disks and 640MB of RA

  • Apple Mail in iOS 8 is broken on my iPad 3

    Hi all. I don't know what is happening with my iOS Mail App after upgrading to iOS8. I even did a full restore of my device (iPad3) configuring it as a new iPad and the problem persists. There is a strong delay in pulling data from the email accounts

  • Configuration setting for syncronizing

    Hi all, I try to syncronizing address book with outlook, but if I klik configuration setting, I can't choise check box for address book, calender etc ( always ask connect internet ). I won't connect internet... Please help...!!! Curve 3G 9300 OS 6.0.

  • Creating a book in 5.5" x 8.5"

    I'd like to create a book in CS3 that uses regular size paper, in landscape format, folded, so that the finished book is 5.5"wide x 8.5 tall." I made all my new documents (chapters) and then put them in a book. The problem is getting it to print righ

  • DS 4.1 SP02 : Error when trying to import XML/XSD-Files

    Hello, i want to import a lot of XML-files with Data Services. I have a XSD file with the XML schema. I've validated the schema against the XML files with XML spy, xmllint and the result is ok. Only Data Services will run on error when i run the job: