zoukankan      html  css  js  c++  java
  • 关于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"),只是在磁盘内暂时创建了缓存而已

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

  • 相关阅读:
    使用PowerDesigner创建表并导入到数据库
    第二次作业——结对项目之需求分析与原型模型设计
    使用Git进行代码管理
    常用
    头文件
    只出现一次的数
    链表实现基础排序算法
    判断链表有公共点
    单链表判环
    二叉树非递归遍历
  • 原文地址:https://www.cnblogs.com/JasonLGJnote/p/7638458.html
Copyright © 2011-2022 走看看