根据字节读取,不能读取中文
![](https://img.haomeiwen.com/i6769622/8e5f8e41ee903ccb.png)
无标题.png
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
//做出界面,做出时间
public class Demo02 extends Frame implements ActionListener
{
//做一个面板,二级容器,可以存放其他组件
Panel panel = new Panel();
//要存放的组件
Label label = new Label("文件:");
TextField text = new TextField(40);
Button button = new Button("打开文件");
TextArea info = new TextArea();
void init()
{//向面板上添加内容
panel.add(label);
panel.add(text);
panel.add(button);
panel.setBackground(Color.orange);
//把面板添加到顶级容器中
add(panel,BorderLayout.NORTH);
//把文本放在界面中间
add(info,BorderLayout.CENTER);
}
//构造函数
Demo02()
{
setSize(500,500);
init();
button.addActionListener(this);//事件授权
setVisible(true);
}
public static void main(String s[])
{
new Demo02();
}
public void actionPerformed(ActionEvent parm1)
{
//文件对话框
FileDialog dlg = new FileDialog(this,"我的对话框");
//打开对话框
dlg.setMode(FileDialog.LOAD);
dlg.show();
//文件全路径
String path = dlg.getDirectory()+dlg.getFile();
System.out.println(path);
//进行读
readFile(path);
}
public void readFile(String path)
{
try
{
//读对象
InputStream fis = new FileInputStream(path);
int data;
String all="";
//循环读写
while((data=fis.read())!=-1)
{
all=all+(char)data;//读出来的内容进行累加
}
fis.close();//释放资源
//把读出来的内容放到文本框上
info.setText(all);
}
catch(Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
网友评论