2010-10-13 61 views
0

我正在創建一個自定義XML編輯器。我的xml文件包含許多特殊的分隔符,例如|•¥‡§等等。但是當我讀取一個文件並在JEditorPane中顯示時,它不會讀取它並顯示其他內容,例如?和一些奇怪的字符。那麼如何讀取和顯示文件就像它一樣。下面是我writen打開文件的代碼:JEditorPane在BufferedReader讀取時不顯示特殊分隔符

void openFile(){ 
    BufferedReader br; 
    try{ 
     File file=open.getSelectedFile();  
     br=new BufferedReader(new FileReader(file)); 
     StringBuffer content=new StringBuffer(""); 
     String line=""; 
     while((line=br.readLine())!=null){ 
     content.append(line+"\n"); 
     } 
     br.close(); 
     getEditorPane().setText(content.toString()); 
     getEditorPane().setCaretPosition(0); 
     edit_tab.setTitleAt(edit_tab.getSelectedIndex(),file.getName()); 
     fileNames.put(edit_tab.getSelectedIndex(),open.getSelectedFile().toString()); 
     tab_title[edit_tab.getSelectedIndex()]=file.getName(); 
    } 
    catch(Exception e){ 
     JOptionPane.showMessageDialog(this,"Error reading file","READ ERROR",JOptionPane.ERROR_MESSAGE); 
    } 
} 

感謝...

+1

請出示你是如何創建的JEditorPane。你是否設置了特定的內容類型? – dogbane 2010-10-13 11:39:21

+0

pane = new JEditorPane(); pane.setFont(new Font(「Courier New」,Font.BOLD,15)); pane.setEditorKitForContentType(「text/xml」,new XmlEditorKit()); pane.setContentType(「text/xml」);這裏XmlEditorKit是類語法高亮 – 2010-10-13 12:16:52

+0

如果有人需要更多關於代碼,然後讓我知道...... – 2010-10-13 12:23:28

回答

1

設置編碼正確的做法是讀取使用的FileInputStream的InputStreamReader和文件,我們可以設置的InputStreamReader的構造函數如下編碼:

 InputStreamReader is; 
     FileInputStream fs; 
     try{ 
       File file=open.getSelectedFile(); 
       fs=new FileInputStream(file); 
       is=new InputStreamReader(fs,"UTF-8"); 
       br=new BufferedReader(is); 
       StringBuffer content=new StringBuffer(""); 
       String line=""; 
       while((line=br.readLine())!=null){ 
        content.append(line+"\n"); 
       } 
       br.close(); 
       getEditorPane().setText(content.toString()); 
      } 
      catch(Exception e){ 

      } 
+1

+1是一個很好的例子。 – trashgod 2010-10-15 21:41:37

+1

您可以設置系統屬性'file.encoding'。 – trashgod 2010-10-18 13:47:56

1

「這一類的構造方法假定默認字符編碼和默認字節緩衝區大小都是適當的自己指定這些值,在FileInputStream上構建一個InputStreamReader。「 - FileReader。您可能需要指定文件的編碼。

+0

非常感謝.....這真的有幫助 – 2010-10-15 08:24:19