【问题标题】:How to set the directory when saving file with filewriter in java?在java中使用filewriter保存文件时如何设置目录?
【发布时间】:2013-12-10 07:52:08
【问题描述】:

您好,我正在使用 NetBeans 来获得更易于使用的 GUI。

我正在尝试使用 FileWriter(不使用可序列化)保存一个我从用户那里获得名称的 txt 文件

我想我可以使用 Serializable 设置文件的保存位置(我不确定)

但是,如果我使用 Serializable,我的代码看起来有点脏,它会导致一些错误。 (我使用 2 个类)

不管怎样,有没有办法在用FileWriter保存txt文件时设置目录?

这是我的代码,用于保存文件。

    public boolean save() {
    try {
        File dir = new File("C:\\Users\\JSK\\Desktop\\BOARD\\data");

        String str = Title_field.getText() + ".txt";
        CheckFile(str);
        CheckCbox();
        area.append("\n Written at :" + date_format.format(now.getTime()));
        FileWriter fw = new FileWriter(str);
        fw.write(area.getText());
        fw.close();
        JOptionPane.showMessageDialog(this, "Successfully Written");
        this.setVisible(false);
        Title_field.setEditable(false);
        area.setEditable(false);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(this, "You Must Create A File First!", "File Missing", JOptionPane.ERROR_MESSAGE);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(this, "I/O ERROR", "Failed to save the file", JOptionPane.ERROR_MESSAGE);
    } catch (FileExistException ex) {
        JOptionPane.showMessageDialog(this, "File Already Exists, Please Change the title", "ERROR", JOptionPane.ERROR_MESSAGE);
        area.setText("");
        return false;
    } catch (CheckboxSelectionException ex) {
        JOptionPane.showMessageDialog(this, "You must select at least one location", "ERROR", JOptionPane.ERROR_MESSAGE);
        Title_field.setText("");
        area.setText("");
        return false;
    }

    return true;
}    

dir 表示我要保存的目录,但它实际上保存在 C:\Users\JSK\Desktop\BOARD

【问题讨论】:

标签: java directory save filewriter


【解决方案1】:

代替这一行:

FileWriter fw = new FileWriter(str);

试试这个:

FileWriter fw = new FileWriter(new File(dir, str));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2020-04-11
    • 1970-01-01
    相关资源
    最近更新 更多