【问题标题】:create and save to a text file using DirectoryChooser使用 DirectoryChooser 创建并保存到文本文件
【发布时间】:2016-04-13 13:34:06
【问题描述】:

我想用我输入的名称创建一个文本文件并将其保存到一个位置。我可以使用 DirectoryChooser 选择位置,但我如何输入文件名。 DirectoryChooser 中是否有此选项。

这是我的代码

public void directoryChooser() {
        DirectoryChooser chooser = new DirectoryChooser();
        chooser.setTitle("Choose location To Save Report"):
        File selectedDirectory = null;
        while(selectedDirectory == null){
        selectedDirectory = chooser.showDialog(null);
        }

        File file = new File(selectedDirectory + "/" + "Report.txt");
        PrintWriter outFile = null;
        try {
            outFile = new PrintWriter(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        for(int i = 0; i<table.getItems().size(); i++){
            outFile.println(table.getItems().get(i).toString());
        }
        outFile.close();
    }

所以我希望它让我可以选择输入要保存的文件的名称。

例如

【问题讨论】:

  • 使用FileChooser?
  • 我认为文件选择器仅用于选择文件??或选择要保存到的文件。文件选择器可以新建文件吗?
  • 是的。 FileChooser 只是在您调用 showSaveDialog 时弹出常规的“保存”对话框。
  • 完全不清楚你在问什么。您希望屏幕截图中缺少哪些功能?

标签: java javafx save


【解决方案1】:

DirectoryChooser 允许您选择目录。如果您想选择一个文件(新的或现有的),请使用FileChooser

public void directoryChooser() {
    FileChooser chooser = new FileChooser();
    chooser.setTitle("Choose location To Save Report"):
    File selectedFile = null;
    while(selectedFile== null){
        selectedFile = chooser.showSaveDialog(null);
    }

    File file = new File(selectedFile);
    PrintWriter outFile = null;
    try {
        outFile = new PrintWriter(file);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    for(int i = 0; i<table.getItems().size(); i++){
        outFile.println(table.getItems().get(i).toString());
    }
    outFile.close();
}

【讨论】:

  • 我不想选择要创建文件的文件。
  • 对不起,我之前尝试过,但我调用的是 showOpenDialog() 没有发现你有 howSaveDialog()。这正是我一直在寻找的。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
相关资源
最近更新 更多