2012-11-19 3 views
2

이 코드는 여러 개의 .java 파일을 읽고 "public [classname]" 또는 "private [classname]"을 추가하고 "System.out.println ([classname])"을 해당 행에 추가하십시오.텍스트 파일의 일부 줄을 수정하려고하는데 그 줄을 다시 파일에 쓸 때 빈 파일이 생깁니다.

문제는 내가 빈 파일로 끝날 뒤에 내가 그 선을 쓸 때입니다

사람이 내가 뭘 잘못 볼 수 있을까요?

private static void work(ArrayList<File> fileList) { 
    for (int i = 0; i < fileList.size(); i++) { 
     replaceLines(fileList.get(i)); 
    } 

} 

public static void replaceLines(File file) { 
    String path = file.getPath(); 
    String fileNameLong = file.getName(); 
    String fileName = null; 
    if (fileNameLong.contains(".java")) { 
     fileName = fileNameLong.substring(0, file.getName().indexOf(".")); 
    } 
    if (fileName != null && fileName != "") { 
     System.out.println(fileName); 
     try { 
      //prepare reading 
      FileInputStream in = new FileInputStream(path); 
      BufferedReader br = new BufferedReader(
        new InputStreamReader(in)); 
      //prepare writing 
      FileWriter fw = new FileWriter(file); 
      PrintWriter out = new PrintWriter(fw); 

      String strLine; 
      while ((strLine = br.readLine()) != null) { 
       // Does it contain a public or private constructor? 
       boolean containsPrivateCon = strLine.contains("private " 
         + fileName); 
       boolean containsPublicCon = strLine.contains("public " 
         + fileName); 

       if (containsPrivateCon || containsPublicCon) { 
        int lastIndexOfBrack = strLine.lastIndexOf("{"); 

        while (lastIndexOfBrack == -1) { 
         strLine = br.readLine(); 
         lastIndexOfBrack = strLine.lastIndexOf("{"); 
        } 

        if (lastIndexOfBrack != -1) { 
         String myAddition = "\n System.out.println(\"" 
           + fileName + ".java\"); \n"; 
         String strLineModified = strLine.substring(0, 
           lastIndexOfBrack + 1) 
           + myAddition 
           + strLine.substring(lastIndexOfBrack + 1); 
         strLine = strLineModified; 
        } 
       } 
       out.write(strLine); 
      } 
     } catch (Exception e) { 
      System.out.println(e); 
     } 
    } 

} 

답변

5

읽고있는 파일에 쓰기를 원할 경우 파일 복사본 (다른 파일명)에 쓰고 출력 파일의 이름을 바꾸거나 RandomAccessFile 인터페이스를 사용하여 파일을 편집해야합니다. 장소.

일반적으로 첫 번째 해결 방법은 두 번째 방법보다 구현하기가 더 쉬운입니다. 입니다. 파일이 거대하지 않은 한 (.java 파일에서는 그렇지 않을 수 있습니다.) 두 번째 파일을 사용할 실제 이유가 없습니다.

5

파일을 플러시하고 닫는 것을 잊었습니다. PrintWriter은 버퍼를 유지하고 명시 적으로 flush()을 지정하지 않으면 데이터가 버퍼에 행복하게 저장되어 출력에 기록되지 않습니다.

그래서 당신은 행 앞에이 PrintWriterPrintStream 만 필요하다고 catch (Exception e) {

out.flush(); 
out.close(); 

참고이를 추가해야합니다. 다른 모든 출력 클래스는 닫을 때 플러시됩니다.

+0

방금'out.write()'다음에 추가했지만 여전히 빈 파일이 있습니다. – code511788465541441

+1

디버거에서 코드를 실행하여 실제로 파일에 아무 것도 쓰지 않도록하십시오. 그리고 ono15에서 말했듯이 입력 파일을 덮어 쓰는 대신 실제로 새 파일을 작성해야합니다. –

관련 문제