其他分享
首页 > 其他分享> > 第五次作业

第五次作业

作者:互联网

 实现的代码

 

package Homework;

import javax.swing.*;
import java.io.*;

public class HomeworkFive {

        public static void main(String[] args) {
            new HomeworkFive().init();
        }
        JFrame jf=new JFrame("第五次作业");
        JTextArea jta=new JTextArea(20,60);
        JButton jb1=new JButton("读取文件");
        JButton jb2=new JButton("写入文件");
        JFileChooser jfc=new JFileChooser(".");
        public void init(){
            jb1.addActionListener(e -> {
                jfc.showOpenDialog(jf);
                File selectedFile = jfc.getSelectedFile();
                try {
                    BufferedReader bis=new BufferedReader(new FileReader(selectedFile));
                    char[] c=new char[1024];
                    int i=0;
                    while ((i=bis.read(c))!=-1){
                        jta.append(new String(c,0,i));
                    }
                    bis.close();
                } catch (IOException o) {
                    o.printStackTrace();
                }
            });
            jb2.addActionListener(e->{
                jfc.showSaveDialog(jf);
                File selectedFile = jfc.getSelectedFile();
                try {
                    BufferedWriter bis=new BufferedWriter(new FileWriter(selectedFile));
                    bis.write(jta.getText());
                    bis.close();
                } catch (IOException o) {
                    o.printStackTrace();
                }

            });
            Box box1 = Box.createHorizontalBox();
            Box box2 = Box.createVerticalBox();
            box1.add(jb1);
            box1.add(jb2);
            box2.add(new JScrollPane(jta));
            box2.add(box1);
            jf.add(box2);
            jf.setVisible(true);
            jf.pack();
            jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    }

实现效果:

自己不太会写,请教了同学做出来的

标签:jfc,selectedFile,作业,add,第五次,new,jf,bis
来源: https://blog.csdn.net/xx_sf/article/details/121078343