import java.awt.BorderLayout;
import java.awt.FileDialog;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class dd extends JFrame{
private static String filepath=null;;
private static TextArea tf = new TextArea("",30,40,TextArea.SCROLLBARS_BOTH);
private static JButton button1=new JButton("打开文件");
private static JButton button2=new JButton("保存文件");
private JPanel panel1=new JPanel();
public dd(){
this.setTitle("传文件");
this.setVisible(true);
this.add(tf,BorderLayout.NORTH);
panel1.add(button1);
panel1.add(button2);
this.add(panel1,BorderLayout.CENTER);
this.pack();
}
public static void main(String[] args) {
new dd();
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
BufferedReader br=null;
FileDialog dialog=new FileDialog(new JFrame(),"打开 指定文件 ",FileDialog.LOAD);
dialog.setVisible(true);
filepath=dialog.getDirectory()+dialog.getFile();
File file=new File(filepath);
try {
br=new BufferedReader(new FileReader((file)));
String content;
StringBuffer sb=new StringBuffer();
while((content=br.readLine())!=null){
sb.append(content+"\n");
}
tf.setText(sb.toString());//添加的内容会覆盖原有的
tf.append(sb.toString());//在原有的基础上追加
} catch (Exception e1) {
e1.printStackTrace();
}
finally{
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}}
}
});
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
FileDialog dialog=new FileDialog(new JFrame(),"保存文件 ",FileDialog.LOAD);
dialog.setVisible(true);
filepath=dialog.getDirectory()+dialog.getFile();
File file=new File(filepath);
FileOutputStream fos =null;
try {
fos = new FileOutputStream(file);
String content=tf.getText();
byte [] b=content.getBytes();
fos.write(b);
fos.close();//关闭输出管道
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
}