Search code examples
javaswingjeditorpane

JEditorPane doesn't display special separators while reading by BufferedReader


I am creating a custom XML editor. My xml file contains lots of special separators such as ¦ • ¥ ‡ § and such other. But when I read a file and display in JEditorPane it doesn't read it and displays something else such as • for • and some weird characters. So how can read and display a file as it is. below is the code i have writen to open the file:

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);
   }
}

thanks...


Solution

  • the correct way to set the encoding is to read the file using FileInputStream and InputStreamReader where we can set encoding in InputStreamReader's constructor as below:

            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){
    
              }