2017-11-16 21 views
0

안녕하세요 저는 현재 대학에서 모듈 용 자바 텍스트 편집기를 작성 중입니다. 서식 파일과 크기를 서식있는 텍스트 파일로 저장하는 데 문제가 있습니다. 현재 인쇄기 메서드를 사용하여 텍스트 영역의 텍스트를 파일에 씁니다. 아래 saveFile 코드를 포함 시켰습니다. 이 게시물은 내 게시물에 문제가있는 경우 정말 죄송합니다, 처음으로 감사드립니다.글꼴 스타일 및 글꼴 크기를 Java의 서식있는 텍스트 파일에 저장하는 방법

public class saveFile implements ActionListener 
{ 

    @Override 
    public void actionPerformed(ActionEvent e){ 
     //allow user to enter file name 
     String s = JOptionPane.showInputDialog("Input name of file:"); 
     String w = ""; 
     try 
     { 
      //Allow user to enter directory 
      w = JOptionPane.showInputDialog("Input Directory where you want the file:\n" 
        + "eg C:\\ for C drive"); 
     } 
     catch(Exception writeFile) 
     { 
      JOptionPane.showMessageDialog(null, "Task could not be completed\nPlease try again" 
        ,"File Write Error", JOptionPane.ERROR_MESSAGE, null); 
     } 
     //try catch block 
     try 
     { 
      //check if fields are null or empty 
      if(!(s.isEmpty() && w.isEmpty()) && (w != null && s != null)) 
      { 
       try 
       { 
        //Create new file and append with .rtf 
        File userFile = new File(w + s + ".rtf"); 
        PrintWriter file = new PrintWriter(userFile); 
        //set files content = text 
        file.print(text.getText()); 
        file.close(); 
        File dir = new File(w); 
        if(dir.exists()) 
        { 
         JOptionPane.showMessageDialog(null, "File " + s + " created\n" + "Saved in " + w, null,JOptionPane.PLAIN_MESSAGE); 
        } 
        else 
        { 
         throw new Exception(); 
        } 

       } 
       catch(Exception fileNotCreatedException) 
       { 
        JOptionPane.showMessageDialog(null,"File not created\n" 
          + "Please check to see directory exists","File Error", 
          JOptionPane.ERROR_MESSAGE, null); 
        fileNotCreatedException.printStackTrace(); 
       } 

      } 
     } 

답변

0

콘텐츠 유형 text/rtf를 사용하여 JTextPane가와 스윙에서 작업하는 경우는, 다음 RTFEditorKit는 StyledDocument에 사용됩니다. 는 HTMLEditorKit도 StyledDocument에 기반함에 따라 HTML 구문은 쉽게로

OutputStream out = new FileOutputStream(userFile); 
StyledDocument doc = textPane.getStyledDocument(); 
StyledEditorKit editorKit = textPane.getStyledEditorKit(); 
editorKit.write(out, doc, 0, doc.getLength()); 

, 때때로, HTML로 첫 번째 실험에 지불 할 수도 있습니다.