import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class MyFrame1 extends JFrame implements ActionListener{
JMenuItem miOpen;
JMenuItem miExit;
JMenuItem miSave;
JTextArea ta;
MyFrame1() {
this.setSize(600,600);
this.setTitle("notepad");
this.setLocationRelativeTo(this);
Container c = this.getContentPane();
JMenuBar mb = new JMenuBar();
this.setJMenuBar(mb);
JMenu mFile = new JMenu("File");
mb.add(mFile);
miOpen = new JMenuItem("open");
miOpen.addActionListener(this);
mFile.add(miOpen);
mFile.addSeparator();
miSave = new JMenuItem("save");
miSave.addActionListener(this);
mFile.add(miSave);
mFile.addSeparator();
miExit = new JMenuItem("exit");
miExit.addActionListener(this);
mFile.add(miExit);
ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);
c.add(sp);

this.setVisible(true);

}

public static void main(String[] args) {
new MyFrame1(); } @Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==miOpen) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(this);
File f = chooser.getSelectedFile();
if (f==null)
return;
try {
FileReader fr = new FileReader(f);
System.out.print(fr.getEncoding());
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
while(str!= null) {
ta.append(str);
ta.append("\n");
str = br.readLine();
}
ta.append("中");
fr.close();
br.close();

} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}else if (e.getSource()== miExit) {
System.exit(0);
}else if (e.getSource()== miSave) {
JFileChooser chooser = new JFileChooser();
chooser.showSaveDialog(this);
System.out.println(chooser.getDialogTitle()); 
System.out.println(chooser.getApproveButtonText()); 
}
}}open一个txt文件,中文显示是乱码,eclipse的环境已经设置成utf-8,操作系统是windows 7,不知道为什么中文是乱码。另外一台机器可以正常显示。

解决方案 »

  1.   

    文件编码的问题,看看这个:http://blog.csdn.net/wula0010/article/details/6862696,读取文件前判断文件编码,再读取文件,如果文件是ue编辑的,第一行的第一个字符前会添加BOM标识,看看这个帖子:http://topic.csdn.net/u/20111026/16/5c91c5e7-f44c-41ed-8a6d-5105604d122b.html,要把前面几个看不见的字符[-124, 49, -107, 51]处理了。
      

  2.   

    中文乱码,是因为文件的编码格式原因,比如你打开的源文件是GBK编码,而你指定的编码格式为UTF-8,中文就会出现乱码。你给你的代码中的这一行:br = new BufferedReader(new InputStreamReader(instream,"utf-8"));你指定源文件是UTF-8编码格式,源文件若非UTF-8编码式就会出乱码。这和你把eclipse的环境已经设置成utf-8是没有什么关系的。