views:

34

answers:

2

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...

+1  A: 

"The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream."—FileReader. You may need to specify the file's encoding.

trashgod
thanks a lot ..... that was really helpful
suraj
+1  A: 

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

          }
suraj
+1 for a good example.
trashgod
You might set the system property `file.encoding`.
trashgod