2014-07-25 3 views
0

각 줄마다 임의의 숫자로 텍스트 파일을 만들려고합니다.자바 : 난수로 큰 텍스트 파일을 만드시겠습니까?

나는 그럭저럭 할 수 있었다. 그러나 나는 무엇인가의 이유로 생성 할 수있는 가장 큰 파일이 768MB이고 나는 15Gbs까지 파일을 필요로한다.

왜 이런 일이 일어나는 것입니까? 내 생각 엔 크기 제한이나 메모리 문제 일까?

내가 작성한 코드입니다 :

public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { 
     //Size in Gbs of my file that I want 
     double wantedSize = Double.parseDouble("1.5"); 

     Random random = new Random(); 
     PrintWriter writer = new PrintWriter("AvgNumbers.txt", "UTF-8"); 
     boolean keepGoing = true; 
     int counter = 0; 
     while(keepGoing){ 
      counter++; 
      StringBuilder stringValue = new StringBuilder(); 
      for (int i = 0; i < 100; i++) { 
       double value = 0.1 + (100.0 - 0.1) * random.nextDouble(); 
       stringValue.append(value); 
       stringValue.append(" "); 
      } 
      writer.println(stringValue.toString()); 
      //Check to see if the current size is what we want it to be 
      if (counter == 10000) { 
       File file = new File("AvgNumbers.txt"); 
       double currentSize = file.length(); 
       double gbs = (currentSize/1000000000.00); 
       if(gbs > wantedSize){ 
        keepGoing=false; 
        writer.close(); 
       }else{ 
        writer.flush(); 
        counter = 0; 
       } 
      } 
     } 
    } 
+0

그 제한을 초과하는 파일을 만들려고하면 어떻게됩니까? – arcy

+0

파일 크기를 아무리 크게 잡아도 768MB로 멈 춥니 다. –

+2

(한숨) 프로그램이 멈추었습니까? 오류 메시지가 나타 납니까? 예외가 있습니까? 디스크 공간이 부족합니까? CPU가 멈추고 화재를 잡습니까? 뭐? – arcy

답변

-2

당신은 당신의 StringBuilder를 청소하지, 그것을 당신이 저장 한 모든 임의의 숫자 문자열을 축적 유지합니다. 당신이 쓰기 직후에 clear()를 써라.

+0

while 루프의 반복마다 (각 줄마다) 새 인스턴스를 만들어서 지워야합니까? –

2

이렇게 코드를 작성하는 방법입니다. 그것은 당신이 원하는 크기도 생산합니다.

public static void main(String... ignored) throws FileNotFoundException, UnsupportedEncodingException { 
    //Size in Gbs of my file that I want 
    double wantedSize = Double.parseDouble(System.getProperty("size", "1.5")); 

    Random random = new Random(); 
    File file = new File("AvgNumbers.txt"); 
    long start = System.currentTimeMillis(); 
    PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")), false); 
    int counter = 0; 
    while (true) { 
     String sep = ""; 
     for (int i = 0; i < 100; i++) { 
      int number = random.nextInt(1000) + 1; 
      writer.print(sep); 
      writer.print(number/1e3); 
      sep = " "; 
     } 
     writer.println(); 
     //Check to see if the current size is what we want it to be 
     if (++counter == 20000) { 
      System.out.printf("Size: %.3f GB%n", file.length()/1e9); 
      if (file.length() >= wantedSize * 1e9) { 
       writer.close(); 
       break; 
      } else { 
       counter = 0; 
      } 
     } 
    } 
    long time = System.currentTimeMillis() - start; 
    System.out.printf("Took %.1f seconds to create a file of %.3f GB", time/1e3, file.length()/1e9); 
} 

인쇄 마침내

Took 58.3 seconds to create a file of 1.508 GB 
관련 문제