2012-04-09 3 views
2

Java로 여러 파일을 만드는 데 문제가 있습니다. 정의 된 디렉토리에 배치 될 n 개의 동일한 파일을 만들고 싶습니다. 웬일인지 지금 당장은 1 파일을 만든 다음 기본적으로 파일을 새로 고치는 첫 번째 파일의 이름으로 새 파일을 만듭니다. 내 글로벌 이름 변수를 업데이트하지 않기 때문에 발생할 수 있다고 생각합니다. 지금까지 내 코드는 다음과 같습니다.Java에서 여러 파일 만들기

import java.io.*; 


public class Filemaker{ 
    //defining our global variables here 

    static String dir = "/Users/name/Desktop/foldername/"; //the directory we will place the file in 
    static String ext = ".txt"; //defining our extension type here 
    static int i = 1; //our name variable (we start with 1 so our first file name wont be '0') 
    static String s1 = "" + i; //converting our name variable type from an integer to a string 
    static String finName = dir + s1 + ext; //making our full filename 
    static String content = "Hello World"; 


    public static void create(){ //Actually creates the files 

     try { 
      BufferedWriter out = new BufferedWriter(new FileWriter(finName)); //tell it what to call the file 
      out.write(content); //our file's content 
      out.close(); 

      System.out.println("File Made."); //just to reassure us that what we wanted, happened 
     } catch (IOException e) { 
      System.out.println("Didn't work"); 
     } 
    } 


    public static void main(String[] args){ 

     int x = 0; 

     while(x <= 10){ //this will make 11 files in numerical order 
      i++; 
      Filemaker.create(); 
      x++; 
     } 
    } 
} 

이 문제를 일으킬 수있는 오류가 있으면 찾아보십시오.

답변

2

finName을 초기화 할 때 한 번 설정하십시오. 대신 create() 함수에서 업데이트해야합니다. 예를 들어 :

public static void create(){ //Actually creates the files 
    String finName = dir + i + ext; 
    try { 
     BufferedWriter out = new BufferedWriter(new FileWriter(finName)); //tell it what to call the file 
     out.write(content); //our file's content 
     out.close(); 

     System.out.println("File Made."); //just to reassure us that what we wanted, happened 
    } catch (IOException e) { 

     System.out.println("Didn't work"); 
    } 
} 
1

첫째, 당신은 당신의 s1 변수의 정적 정의에 i 변수를 사용하고 있습니다. 이것은 나에게 이상하게 보였고, 나는 그것이 당신이 반복해서 다시 정의 될 것으로 기대한다고 생각하게 만든다.

대신 실제로함수 내에서 s1 변수를 다시 정의하여 실제로 증가시킵니다.

또한 이와 같은 문제를 해결할 때 System.out.println() 문을 사용하여 출력을 콘솔에 인쇄하여 프로그램 실행을 추적 할 수 있습니다. 고급 요구 사항을 위해 로깅 솔루션이나 IDE의 디버거를 사용하여 프로그램 실행을 추적하고 중단 점을 삽입하십시오.

+1

감사합니다. 정말 도움이되었습니다. 디버깅 습관이 부족해서 죄송합니다. 웹 개발/프로그래밍이 아닌 새로운 기능입니다. – Kronos

+1

걱정할 필요가 없습니다. 방금 도움이 될만한 정보라고 생각했습니다. 디버거가 없으면 쓸모가 없다.) – jmort253

0

문자열이 변경 불가능하므로 finName은 첫 번째 초기화 후에 변경되지 않습니다.

작성 메소드에서 파일 경로를 다시 만들어야합니다.