[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 320
  • Last Modified:

Sizes of Files and Zipfiles, etc

I am working on an application that, for part of it, a zip file is created. Where the zipfile is placed depends on its size (i.e. if it causes the current directory to hit capacity or not).  

In doing a little poking around, this is what I have found:
- In order to determine the size a zip file will be that holds a given set of files, I actually need to construct it.
- A File object is immutable, so once it is created, I cannot make it 'point' to another directory/filepath.

Based on this, the only thing I can figure is that if the zip file is too large, I will actually need to repeat the process of creating it in order to put it in a secondary directory if the first hits capacity.

I would like to know if others agree with this or if there is another reasonable way to handle this.
0
kls1
Asked:
kls1
  • 4
  • 2
  • 2
  • +2
3 Solutions
 
sciuriwareCommented:
I would never 'reuse' a File object. Nowadays we worry about Gb, not about some bytes.

If you can not predict the size of the zipfile, it's better to create it in a place
with lots of space and later to copy it.
The zipping process takes a lot of CPU and copying is cheap.

Beware that some files GROW when zipped, e.g. "white noice" files.

;JOOP!
0
 
kls1Author Commented:
The question is...how do you "move" a zip file in Java? Since a File object is immutable....
0
 
kls1Author Commented:
From what I see, and I could be wrong:

You construct a File object with the path where you want your Zip file
Then you construct your zip from from that File object

Is there something I'm missing? So, once I have a zip file constructed, how can I move it?
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
Mayank SAssociate Director - Product EngineeringCommented:
You can always copy the file from one location to another (using FileInputStream/ FileOutputStream) and then delete the previous one.

http://www.javaalmanac.com/egs/java.io/CopyFile.html 
0
 
sciuriwareCommented:
A File object is only there to administer a file on disk.

On MSWindows XP and 2003 you can move a file in JAVA
by renaming it.

File x = new File("D:/myfolder/myfile");
.......................... // create the file, close it.
x.renameTo("F:/theirfolder/theirfile");

Would the latter return   false
then you should copy it yourself.

;JOOP!
0
 
rama_krishna580Commented:
Hi,

Sample code here...:::

import java.io.File;
import java.util.*;
/***************************************************************** ******************************
* This program finds the actual content size of the file not the size of the file in the disk.
* Eg: Check the 1 Byte text file for its actual content size and the size of that same file in the
* disk.
******************************************************************************* ****************/

public class FindFileSize
{
double fileSizeKB;



public FindFileSize()
{
/**Specify the location and name of the file whose size is to be found **/

File f = new File("C:\\arulTest\\arul2.zip");

String fileLength = String.valueOf(f.length());
int fileLengthDigitCount = fileLength.length();
double fileLengthLong = f.length();
double decimalVal = 0.0;
String howBig = "";

System.out.println("fileLengthDigitCount is..."+fileLengthDigitCount);

if(f.length()>0)
{
if(fileLengthDigitCount < 5)
{
fileSizeKB = Math.abs(fileLengthLong);
howBig = "Byte(s)";
}
else if(fileLengthDigitCount >= 5 && fileLengthDigitCount <=6)
{
fileSizeKB = Math.abs((fileLengthLong/1024));
howBig = "KB";
}
else if(fileLengthDigitCount >= 7 && fileLengthDigitCount <= 9)
{
fileSizeKB = Math.abs(fileLengthLong/(1024*1024));
howBig = "MB";
}
else if(fileLengthDigitCount >9)
{
fileSizeKB = Math.abs((fileLengthLong/(1024*1024*1024)));
decimalVal = fileLengthLong%(1024*1024*1024);
howBig = "GB";
}
}
System.out.println("....bytes....."+fileSizeKB);
String finalResult = getRoundedValue(fileSizeKB);
System.out.println("\n....Final Result....."+finalResult+" "+howBig);
}

private String getRoundedValue(double decimalVal)
{
System.out.println("\nThe first call......."+decimalVal);

long beforeDecimalValue = decimalTokenize(decimalVal,1);
long afterDecimalValue = decimalTokenize(decimalVal,2);
long decimalValueLength = String.valueOf(afterDecimalValue).length();
long dividerVal = divider(decimalValueLength-1);
long dividedValue = afterDecimalValue/dividerVal;
String finalResult=String.valueOf(beforeDecimalValue)+"."+String.valueOf(dividedValue) ;

System.out.println("\nfinalResult......."+finalResult);

return finalResult;
}

private long divider(long argLength)
{
long varDivider=1;

for(int i=0;i<(argLength-1);i++)
{
varDivider=varDivider*10;
}

return varDivider;
}

private long decimalTokenize(double decimalVal,int position)
{

long returnDecimalVal=0;
String strDecimalVal="";

if(decimalVal >0)
strDecimalVal = String.valueOf(decimalVal);

if(strDecimalVal.length()>0)
{
StringTokenizer decimalToken = new StringTokenizer(strDecimalVal,".");
//System.out.print("\n String tokenized successfully"+decimalToken.countTokens());
//int count = decimalToken.countTokens();

if(position==1)
{
returnDecimalVal = Long.parseLong(decimalToken.nextToken());
}
else if(position==2)
{
decimalToken.nextToken();
returnDecimalVal = Long.parseLong(decimalToken.nextToken());
}
}
return returnDecimalVal;
}

/**
*
* @param args
*/
public static void main(String[] args)
{
FindFileSize findFileSize = new FindFileSize();
}
}

R.K
0
 
mightyoneCommented:
you can create your file later:
zip in an byte[] and serialize whereever and whenever
e.g.

   public static byte[] createZip (String[] filenames, String path){
      logger.entering( "ZipUtil", "createFiles" );
      ZipOutputStream zos = null;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int len;
      try{
         zos = new ZipOutputStream(baos);
         byte [] buf = new byte[1024];
         for (int idx = 0; idx < filenames.length;idx++){
            File oneFile = new File(path+filenames[idx]);
           
            if (oneFile.isFile()){
               ZipEntry ze = new ZipEntry(oneFile.getName());
               FileInputStream fis = new FileInputStream(oneFile);
               
               zos.putNextEntry(ze);
               ze.setTime(oneFile.lastModified());
               while ((len = fis.read(buf)) >= 0){
                  zos.write(buf, 0, len);
                  }
               zos.closeEntry();
               logger.info("added "+ze.getName()+" to ZipContainer. Ratio : "
                  +ze.getCompressedSize()*100/ze.getSize()+" %");
               fis.close();
               }
            }
         }
      catch(IOException e){
         logger.severe("IO Error! ");
         }
      finally{
         if (zos!= null){
            try {
               zos.close();
               }
            catch(IOException e){
               logger.severe("IO Error! ");
               }
            }
         zos = null;
         }
      return baos.toByteArray();
      }

and for serializing.
   public static int writeByteArray(String name, byte[] data)
   {    
      int x = 0;
      OutputStream out = null;
      try
      {
         out = new FileOutputStream(name);
         out.write(data);        
      }
      catch (IOException io)
      {
         logger.warning("Severe!!!! Write Failure \t"+name);
         io.printStackTrace();
         x = -1;
      }
     
      finally
      {
         if (out != null)
         {
            try
            {
               out.close();
            }
            catch (IOException ii)
            {
               logger.warning("Error closing stream");
            }
         }
      }
      return x;
   }
0
 
kls1Author Commented:
mightyone: So, your method above doesn't actually write the data to the hard drive until the writeByteArray method? (i.e. createZip only creates the zip in RAM and gets the size of the zip?)
0
 
kls1Author Commented:
mightyone: I see that you are sending in a path to the writeByteArray, so I'm guessing it is actually writing this zip file to the hard drive during this method, correct?
0
 
mightyoneCommented:
yes...
zip is created in RAM.

the path is to read the files to zip from, see :>>File oneFile = new File(path+filenames[idx]);

first time you write is here:
 out = new FileOutputStream(name);//name should be somehow like "c:\tmp\file.zip"
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 4
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now