Click to See Complete Forum and Search --> : Writing to a zip file


Apurva
April 5th, 1999, 03:53 PM
Hey friends,
i want to write 3 array of shorts to a zip file using object serialisation. I tried doing it using zipoutputstream, but it says that the zip entry i am using is not ok. can anyone please send me a code which will enable me to read and write array of shorts to a ZIP file.
Regards,
Apurva

Bogdan Matasaru
April 6th, 1999, 11:00 AM
Try this. It should work. Maybe you had problems with the putNextEntry/getNextEntry calls.


import java.io.*;
import java.util.zip.*;

public class ZipShorts
{
public static void main (String[] args)
{
System.out.print ("Create the zip file ? <y/n> ");
boolean create = false;
try
{
String result = new BufferedReader (new InputStreamReader (System.in)).readLine ();
create = result.toUpperCase ().startsWith ("Y");
}
catch (Exception e)
{
}
if (create)
{
try
{
System.out.println ("Enter the arrays of shorts as lines of space-separated numbers.");
System.out.println ("Finish with an empty line.");
ZipOutputStream zos = new ZipOutputStream (new FileOutputStream ("Shorts.zip"));
zos.putNextEntry (new ZipEntry ("Shorts"));
ObjectOutputStream oos = new ObjectOutputStream (zos);
try
{
String s = "";
while (true)
{
s = new BufferedReader (new InputStreamReader (System.in)).readLine ();
if (s.length () == 0)
break;
StreamTokenizer st = new StreamTokenizer (new StringReader (s));
st.parseNumbers ();
java.util.Vector vals = new java.util.Vector ();
while (st.nextToken () != StreamTokenizer.TT_EOF)
{
if (st.ttype != StreamTokenizer.TT_NUMBER)
{
System.out.println ("Bad input: " + st.sval);
System.exit (1);
}
vals.add (new Short ((short)st.nval));
}
short[] array = new short[vals.size ()];
for (int i = 0;i < array.length;i++)
array[i] = ((Short)vals.get (i)).shortValue ();
oos.writeObject (array);
}
}
catch (IOException ioe)
{
}
zos.close ();
}
catch (Exception e)
{
e.printStackTrace ();
}
}
else
{
try
{
ZipInputStream zis = new ZipInputStream (new FileInputStream ("Shorts.zip"));
zis.getNextEntry ();
ObjectInputStream ois = new ObjectInputStream (zis);
try
{
for (int i = 1;;i++)
{
short[] array = (short[])ois.readObject ();
String s = i + ") ";
for (int j = 0;j < array.length;j++)
{
if (j > 0)
s += ", ";
s += array[j];
}
System.out.println (s);
}
}
catch (IOException ioe)
{
}
}
catch (Exception e)
{
e.printStackTrace ();
}
}
}
}