(java/javafx)尝试创建和写入文件只会创建空白文件

ws51t4hk  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(272)

我正在尝试创建一个gui,用户在其中填写textfields,然后程序创建一个txt文件并相应地写入其中。
目前,程序用指定的名称创建文件,但没有写入任何内容(txt文件为空)。我做错了什么?
代码:

try {
          File myObj = new File(mNameTF.getText()+".txt");
          if (myObj.createNewFile()) {
            System.out.println("File created: " + myObj.getName());
            FileWriter myWriter = new FileWriter(mNameTF.getText()+".txt");
            BufferedWriter bw = new BufferedWriter(myWriter);
            bw.write("Movie: " +mNameTF.getText());
            bw.newLine();
            bw.write("Actors: "+actorsTF.getText());
            bw.newLine();
            bw.write("Director: "+ dirTF.getText());
            bw.newLine();
            bw.write("Producer: "+ prodTF.getText());
            bw.newLine();
            bw.write("Info: "+descriptionTA.getText());
            primaryStage.setScene(sceneA);
            } else {
              System.out.println("File already exists.");

            }
          } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
          }
0dxa2lsx

0dxa2lsx1#

bufferedwriter以大批量写入文本以减少操作系统调用量。这意味着文本不会立即出现在文件中。如果你想强迫它写它存储的文本以备将来写,你必须调用它的 flush() 方法。
你也没有关闭writer,这是1。保持文件打开且不可编辑2。使用不必要的内存。你可以通过打电话来关闭writer close() ,这也会刷新它。

jbose2ul

jbose2ul2#

你应该使用“尝试资源”。

try{
    File myObj = new File(mNameTF.getText()+".txt");
    if (myObj.createNewFile()) {
        System.out.println("File created: " + myObj.getName());
        try( FileWriter myWriter = new FileWriter(mNameTF.getText()+".txt");
             BufferedWriter bw = new BufferedWriter(myWriter) ){
            bw.write("Movie: " +mNameTF.getText());
            bw.newLine();
            bw.write("Actors: "+actorsTF.getText());
            bw.newLine();
            bw.write("Director: "+ dirTF.getText());
            bw.newLine();
            bw.write("Producer: "+ prodTF.getText());
            bw.newLine();
            bw.write("Info: "+descriptionTA.getText());
            primaryStage.setScene(sceneA);
        }
    } else {
        System.out.println("File already exists.");          
    }
} catch (IOException e){
    System.out.println("An error occurred.");
    e.printStackTrace();
}

这样,缓冲写入程序将在内部try块的末尾自动关闭。
一种新的处理方法是使用 Files 班级。

try( 
   BufferedWriter bw = Files.newBufferedWriter​(
       Paths.get(mNameTF.getText()+".txt"), 
       StandardOpenOption.CREATE_NEW
   ) 
){
   //just the write code.
} catch(FileAlreadyExistsException exists){
   //this is where you'll handle already exists exception.
} catch(IOException ioe){
   //handle ioexception here.
   //if you don't want to handle it (which you aren't).
   throw new RuntimeException(ioe);
}

相关问题