2013-03-22 38 views
-4

我目前有一個工作程序,通過填充零來創建任意大小的文件。這很好,但是我需要做的這些文件的大小是千兆字節,並且這種方法將永遠需要,才能做到這一點。如果任何人都可以閱讀這些代碼,並提供提示,以使其更快,這將不勝感激。優化文件製作程序

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(); 
} 

}

+1

...這就像問「我怎麼壓縮5GB文件到10KB」 – Doorknob 2013-03-22 12:56:39

+0

林要求更快的方法來填充這個代碼似乎是故意慢文件 – user2007843 2013-03-22 12:58:40

+0

。 – harold 2013-03-22 13:00:01

回答

3
  1. 寫在同一時間超過一個字節。一次寫入4096個字節的倍數。
  2. 每次寫入後都不要刷新流。
  3. 而不是查詢文件大小,每次寫入時只增加size
+0

謝謝,但我將如何增加大小? – user2007843 2013-03-22 14:20:48

+0

嗯,'size + =你寫了多少字節;'? – 2013-03-22 15:10:36

+0

這就是我在想什麼,但如果我寫這樣的文件'output.write(「0000000 ....」)'我怎麼會在'你寫多少字節'中定義? – user2007843 2013-03-22 15:18:10