如果存在则向文件添加文本,如果不在 java 中则创建带有文本的文件

Add text to the file if exist and create file with text if not in java

我需要向现有文件添加文本(如果用户在开始时选择文件 - 按下阅读按钮)

fileread = fileChooser.showOpenDialog(primaryStage);

或者如果文件不存在(用户没有在开始时从读取按钮选择文件),同样的保存按钮,打开一个

 File filesave = fileChooser.showSaveDialog(primaryStage);

并一如既往地保存文件,如果用户没有选择的话。

我有方法 savefield - 从 HTMLEditor javaFX 保存文本

@FXML public void savefiled() throws FileNotFoundException, IOException {
      Stage primaryStage = null;
      String stringHtml = HTMLEditor_go.getHtmlText();

if(fileread.getPath().equals("")||fileread.getPath() == null){ //this line gives me a NULL

    Files.createDirectories(Paths.get("./src/path/my_text/"));
    FileChooser fileChooser = new FileChooser();
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("HTML files (*.html)", "*.html");
        fileChooser.getExtensionFilters().add(extFilter);

   File defaultDirectory = new File(System.getProperty("user.dir")+"/src/path/my_text/");
    fileChooser.setInitialDirectory(defaultDirectory);
    File filesave = fileChooser.showSaveDialog(primaryStage);
    filesave.createNewFile();
    SaveFile(stringHtml, filesave);

}else{ File fileget = new File(fileread.getPath()); 
fileget.createNewFile();  
SaveFile(stringHtml, fileget);} }

保存文件是

private void SaveFile(String content, File file){
try {Writer write = new BufferedWriter (new FileWriter(file));
     write.write(content);
     write.close(); 
    } catch (IOException ex) {    }}

据我所知,如果用户没有选择要打开的文件,那么 fileread 仍将为空。所以你只需要测试一下。替换

if(fileread.getPath().equals("")||fileread.getPath() == null){

    // ...
}

if (fileread == null) {
    // ...
}

(或者可能

if (fileread == null || fileread.getPath().equals("") || fileread.getPath() == null) {
    // ...
}

虽然我真的不明白后两个测试中的任何一个如何评估为真)。