Question

I currently have a working program that creates a file of any desired size by populating it with zeroes. This is great but the size of the files I need to do this for are Gigabytes, and this method would take forever in order do do this. If anyone can read this code over and offer tips to make this faster it would be appreciated.

public class fileMaker
{
 public static void main(String[] args) throws IOException
 {
     fileMaker fp = new fileMaker();


     Writer output = null;
     File f = new File(args [1]);
     output = new BufferedWriter(new FileWriter(f, true));
     output.write("0");


     long size = fp.getFileSize(args[1]);

     long mem = Long.parseLong(args[0]) * 1073741824; //1 Gigabyte = 1073741824 bytes        


     while(size < mem)
     {
            output.write("0");


            output.flush();

            size = fp.getFileSize(args[1]);
            //System.out.println(size + " bytes completed out of " + mem);

            double avg = (double)size / mem * 100;

            System.out.println(avg + "% complete");

     }
     output.close();
     System.out.println("Finished at - " + size / 1073741824  + " Gigabytes");

 }


private long getFileSize(String fileName) 
{
    File file = new File(fileName);        
    if (!file.exists() || !file.isFile()) 
    {
        System.out.println("File does not exist");
        return -1;
    }
    return file.length();
}

}

Was it helpful?

Solution

  1. Write more than one byte at a time. Write some multiple of 4096 bytes at a time.
  2. Don't flush the stream after every write.
  3. Instead of querying for the file size, just increment size every time you write.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top