2013-11-10 2 views
0

내 GUI에 charList.txt라는 텍스트 파일을 읽은 다음 GUI를 통해 몇 가지 사항을 변경했습니다. 나는 모든 변경 사항을 동일한 텍스트 파일에 저장하려고하지만 어떻게해야할지 모르겠다. 그래서 new.text라는 새로운 텍스트 파일을 만들고 charList.text를 덮어 쓰게 이름을 바꿉니다. 그러나 실패했습니다. 누군가 제안 해 줄 수 있습니까? 감사!java에서 텍스트 파일을 덮어 쓰는 방법은 무엇입니까?

 try { 
       FileWriter edit = new FileWriter("new.txt"); 
       PrintWriter pedit = new PrintWriter(edit); 
       FileReader fr = null; 
        String line = "null"; 
        try{ 
         fr = new FileReader("charList.txt"); 
        } 
        catch (FileNotFoundException e1){ 
         e1.printStackTrace(); 
        } 
        BufferedReader bf = new BufferedReader(fr); 

        while(line != null){ 
         try{ 
          line = bf.readLine(); 
         } 
         catch (IOException e1){ 
          e1.printStackTrace(); 
         } 
         if (line != null){ 
          fields = line.split("\t"); 
          if (Integer.parseInt(idField.getText()) != Integer.parseInt(fields[0])){ 
           pedit.println(line); 
          } 
          else{ 
           pedit.println(Integer.parseInt(idField.getText()) + "\t" + moneyBefore + "\t" + userName + "\t" + fields[3] + "\t" + fields[4] + "\t" 
             + fields[5] + "\t" + moneyAfter); 
          } 
         } 
        } 
        pedit.close(); 
        bf.close(); 
        File old = new File("charList.txt"); 
        old.delete(); 
        File oldfile =new File("new.txt"); 
        File newfile =new File("charList.txt"); 

        if(oldfile.renameTo(newfile)){ 
         System.out.println("Rename succesful"); 
        }else{ 
         System.out.println("Rename failed"); 
        } 

      } 
       catch (IOException e1) { 
       e1.printStackTrace(); 
       } 

     } 
    } 

답변

1

두 스트림을 모두 닫습니다. 이름 바꾸기 전에 oldFile을 삭제하십시오.

+0

'finally'블록 내부의 스트림도 닫으십시오. FindBugs는 여기서 리소스를 적절하게 닫는 몇 가지 기본 사항을 가르치는 데 도움이 될 수 있습니다. – jbindel

+0

어떻게 이전 파일을 삭제합니까? 스트림에 의해 당신은'br'과'pedit'을 올바르게 의미합니까? – user2350622

+0

1) File.delete(). 2) 예 ... 그것이 그가 의미하는 것입니다. –

관련 문제