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",JOptionPa开发者_Python百科ne.ERROR_MESSAGE);
}
}
thanks...
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){
}
"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.
精彩评论