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"),只是在磁盘内暂时创建了缓存而已

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

  • 相关阅读:
    kafka 0.10.2 cetos6.5 集群部署
    zookeeper3.4.9 centos6.5 集群安装
    centos6.5 scala环境变量
    用易语言写个简单的小爬虫其中的关键点
    MYSQL错误码2059解决办法
    python随机生成经纬度(用于爬虫参数伪造)
    frida框架hook获取方法输出参数(常用于简单的so输出参数获取,快速开发)
    安卓日常开发和逆向中常用的shell命令与非shell命令
    从了解机器学习开始
    numpy的使用方法
  • 原文地址:https://www.cnblogs.com/JasonLGJnote/p/7638458.html
Copyright © 2011-2022 走看看