• 关于Java里面File类创建txt文件重复???


    private JButton getOpenButton() {
    if (openButton == null) {
    openButton = new JButton();
    openButton.setText("写入文件"); // 修改按钮的提示信息
    openButton.addActionListener(new java.awt.event.ActionListener() {
    // 按钮的单击事件
    public void actionPerformed(ActionEvent e) {
    // 创建文件对象
    File file = new File("word.txt");
    try {
    // 创建FileWriter对象
    FileWriter out = new FileWriter(file);
    // 获取文本域中文本
    String s = jTextArea.getText();
    out.write(s); // 将信息写入磁盘文件
    out.close(); // 将流关闭
    } catch (Exception e1) {
    e1.printStackTrace();
    }
    }
    });
    }
    return openButton;
    }

    private JButton getCloseButton() {
    if (closeButton == null) {
    closeButton = new JButton();
    closeButton.setText("读取文件"); // 修改按钮的提示信息
    closeButton.addActionListener(new java.awt.event.ActionListener() {
    // 按钮的单击事件
    public void actionPerformed(ActionEvent e) {
    File file = new File("word.txt"); // 创建文件对象
    try {
    // 创建FileReader对象
    FileReader in = new FileReader(file);
    char byt[] = new char[1024]; // 创建char型数组
    int len = in.read(byt); // 将字节读入数组
    // 设置文本域的显示信息
    jTextArea.setText(new String(byt, 0, len));
    in.close(); // 关闭流
    } catch (Exception e1) {
    e1.printStackTrace();
    }
    }
    });
    }
    return closeButton;

    }

      如上程序段,刚开始我都认为两个按键都重新创建了woed.txt文件,那么不是覆盖了吗?

      实际上不是的,File类创建word.txt文件并不是真的创建,真要创建,要用file.creatNewfile()才行,实际上两个地方都new File("word.txt"),只是在磁盘内暂时创建了缓存而已

    而且因为第一个按键已经创建了,第二个就直接用它(名称一样)。

  • 相关阅读:
    MyBatis:分页的实现
    Mybatis之配置文件
    Java之创建线程的方式四:使用线程池
    Java之创建线程的方式三:实现Callable接口
    Java之线程通信的应用:经典例题:生产者/消费者问题
    Java之线程通信的方法
    Java之解决线程安全问题的方式三:Lock锁
    Java之同步方法处理实现Runnable接口的线程安全问题
    Java之同步方法处理继承Thread类的线程安全问题
    01 while 循环输入1 2 3 4 5 6 8 9 10
  • 原文地址:https://www.cnblogs.com/JasonLGJnote/p/7638458.html
Copyright © 2020-2023  润新知