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"),只是在磁盘内暂时创建了缓存而已,而且因为第一个按键已经创建了,第二个就直接用它(名称一样)。

  • 相关阅读:
    day5-Python学习笔记(九)json数据类型
    day5-Python学习笔记(八)内置函数
    day4-Python学习笔记(七)函数与模块
    day4-Python学习笔记(六)监控日志,集合数据类型
    day4-Python学习笔记(五)文件读写,文件内容修改
    day3-python学习笔记(四)字符串方法
    day3-python学习笔记(三)字典、元组
    day3-python学习笔记(二)list(数组)
    变量
    网络编程
  • 原文地址:https://www.cnblogs.com/JasonLGJnote/p/11159895.html
Copyright © 2011-2022 走看看