2014-11-12 3 views
0

메모 패드과 같은 프로그램을 만들고 싶습니다. JTextArea 안에 텍스트를 입력하고 을 클릭하면, 으로 저장되고 프로그램은 JTextArea 안에 입력 된 텍스트로 작업 영역 내에 텍스트 파일을 만듭니다. 문제는 내가 저장을 클릭하면 프로그램이 텍스트 파일을 만들 수 있지만 텍스트 영역 안에 입력 한 텍스트는 생성 된 텍스트 파일 안에 저장되지 않습니다. 텍스트 파일의 "Text"입니다. 나는 TextArea 안에있는 텍스트를 얻기 위해 getText() 방법을 사용했습니다.FileWriter 및 Printwriter를 사용하여 텍스트 파일에 텍스트를 쓸 수 없다

import javax.swing.*; 
import java.awt.event.*; 
import java.awt.*; 
import java.io.*;  
public class TextAreaWithMenus extends JFrame implements ActionListener { 
    JTextArea area; 
    JMenuBar menubar; 
    JMenu option; 
    JMenuItem menuitem; 
    File file; 
    FileWriter fwriter; 
    PrintWriter pwriter; 
    String order[] = {"Save as","Edit"}; 

    public TextAreaWithMenus() { 
     setSize(new Dimension(500,500)); 
     setDefaultCloseOperation(this.EXIT_ON_CLOSE); 
     setLocationRelativeTo(null); 
     setResizable(false); 
     setLayout(null); 
     area = new JTextArea(); 
     menubar = new JMenuBar(); 
     option = new JMenu("File"); 
     for(String call : order) { 
      menuitem = new JMenuItem(call); 
      option.add(menuitem); 
      menuitem.addActionListener(this); 
     } 
     this.add(menubar); 
     menubar.setBounds(0,0,500,30); 
     menubar.add(option); 
     this.add(area); 
     area.setBounds(0,30,500,470); 
     area.setLineWrap(true); 
     area.setWrapStyleWord(true); 
     try{ 
      file = new File("C://Users/LunaWorkspace/TestProject/src/Text"); 
      fwriter = new FileWriter(file); 
      pwriter = new PrintWriter(fwriter,true); 
     }catch(Exception e) {}   
     setVisible(true); 
    }//END OF CONSTRUCTOR 

    public void save() { 
     try { 
      if(!file.exists()) { 
       try { 
        file.createNewFile(); 
        pwriter.print(area.getText()); 
        System.out.println(area.getText()); 
        System.out.println("Saved complete"); 
       }catch(Exception ef) { 
        ef.printStackTrace(); 
        System.err.print("Cannot Create"); 
       }     
      }else if(file.exists()) { 
        pwriter.print(area.getText()); 
        System.out.println(area.getText()); 
        System.out.println("Overwrite complete"); 
      } 
     } catch(Exception exp) { 
      exp.printStackTrace(); 
      System.err.println("Cannot Save"); 
     }  
    } 

    public void actionPerformed(ActionEvent ac) { 
     String act = ac.getActionCommand();   
     if(act.equals("Save as")) { 
      save(); 
     }else if(act.equals("Edit")) {} 
    } 

    public static void main (String args[]) { 
     EventQueue.invokeLater(new Runnable() { 
           public void run() { new TextAreaWithMenus();} }); 
    } 
} 

답변

1

저장이 버퍼링 될 때 flush를 호출해야합니다. 이 작동합니다 :

public void save() { 
    try { 
     if (!file.exists()) { 
      try { 
       file.createNewFile(); 
       pwriter.print(area.getText()); 
       System.out.println(area.getText()); 
       System.out.println("Saved complete"); 

      } catch (Exception ef) { 
       ef.printStackTrace(); 
       System.err.print("Cannot Create"); 
      } 

     } else if (file.exists()) { 
      pwriter.print(area.getText()); 
      System.out.println(area.getText()); 
      System.out.println("Overwrite complete"); 
     } 
    } catch (Exception exp) { 
     exp.printStackTrace(); 
     System.err.println("Cannot Save"); 
    } finally { 
     pwriter.flush(); 
    } 
} 
+0

감사합니다. pwriter.flush() 메서드와 pwriter.close() 메서드의 차이점은 무엇입니까? 방금 close() 메서드를 시도했을 때 텍스트 파일의 새 텍스트 집합으로 텍스트를 덮어 쓰려면 프로그램을 다시 실행해야하는 것으로 나타났습니다. – ZeroCool

+0

'flush'는 버퍼를 플러시하고'close'는 처음 플러쉬를 호출하고 리소스를 가비지 수집하도록 해제합니다. 그런 다음 내부 상태를 지워 메모리를 회수 할 수 있기 때문에 null 포인터 예외를 throw하는 것이 아니라 거부하기 때문에 닫을 수있는 항목을 다시 사용할 수 없습니다. 'File'은 운영 체제에 대한 네이티브 파일 핸들을 가지고 있습니다. close를 호출하면 jvm이 해당 핸들을 닫아 OS가 해당 리소스를 해제 할 수있게합니다. 운영체제에서 프로세스를 열어 둘 수있는 파일의 수에 제한이 있기 때문에 파일을 끝내면'close'를 호출해야합니다. – simbo1905

1

당신이 끝난 후 pwriter.close()와 작가를 닫아야합니다 :

는 프로그램입니다. 그렇지 않으면 텍스트가 플러시되지 않았고 아무 것도 쓸 수 없습니다.

0

작성자에서 작성자를 만들고 저장 메서드에서 반복적으로 쓰기 좋은 연습. 새 파일을 만들고 이전 스트림에 쓰면 예기치 않은 동작이 발생할 수 있습니다.

save/write 메서드에서 스트림을 작성하고 닫습니다.

그러면 파일이 이미 있는지 확인할 필요가 없습니다. 새 FileWriter (file)가 기존 파일을 덮어 씁니다.

관련 문제