⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 filedemo2.java

📁 JAVA学习源代码,大家可以好好参考,请多提宝贵意见
💻 JAVA
字号:
//FileDemo2.java
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FileDemo2
    extends JFrame
    implements ActionListener {
  private JTextArea inputTextArea;   //文件内容显示区域
  private JButton openButton;            //打开按钮
  private JLabel label;                         //提示用户打开文件
  private FileInputStream inFile;        //输入文件流
  private File file;
  byte[] bufferArray=new byte[4096];
  public FileDemo2(){
    Container container = getContentPane();
    container.setLayout(new FlowLayout());
    label = new JLabel("The file test.txt content :");
    label.setForeground(Color.red);
    container.add(label, BorderLayout.NORTH);
    inputTextArea = new JTextArea("", 10, 20);
    inputTextArea.setEditable(false);
    container.add(new JScrollPane(inputTextArea), BorderLayout.CENTER);
    openButton = new JButton("Open");
    container.add(openButton, BorderLayout.SOUTH);
    openButton.addActionListener(this);
    setSize(300, 300);
    setVisible(true);
  }
  //事件处理
  public void actionPerformed(ActionEvent event) {
    if (event.getSource() == openButton) {
      try {
        file=new File("test.txt");
        int fileLength=(int)file.length();
        inFile = new FileInputStream(file);
        //将用户写入信息保存到文件
        inFile.read(bufferArray, 0, fileLength);
        String str=new String();
        for(int i=0; i<fileLength; i++){
          str+=(char)bufferArray[i];
        }
        inputTextArea.setText(str);
        inFile.close();
        //提示操作成功
        JOptionPane.showMessageDialog(this,"The file test.txt has been opened !");
      }
      catch (IOException e) {
        //发生异常时,给出提示信息
        JOptionPane.showMessageDialog(this,"Error when openning file or closing the file !"
                                           , "Error", JOptionPane.ERROR_MESSAGE);
        System.exit(1);   //退出
      }
    }
  }

  public static void main(String[] args){
    FileDemo2 fileDemo2 = new FileDemo2();
    fileDemo2.setDefaultCloseOperation(
        JFrame.EXIT_ON_CLOSE);
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -