需要 JavaFX 帮助写入 .txt 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24565539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In need of JavaFX help writing to a .txt file
提问by planker1010
I need to create a JavaFX project that creates a gui to input a name and password. I have created the panes, and set the stage. The items show correctly, however I cant upon button click get the info to write to the file. It creates the file but will not store the data. I need to be able to several names and passwords so I can create a reader login program to check the .txt file. Here is the code I have. Thanks.
我需要创建一个 JavaFX 项目来创建一个 gui 来输入名称和密码。我已经创建了窗格,并设置了舞台。项目显示正确,但是我无法在单击按钮时获取信息以写入文件。它会创建文件但不会存储数据。我需要能够使用多个名称和密码,以便我可以创建一个阅读器登录程序来检查 .txt 文件。这是我的代码。谢谢。
import javax.swing.JOptionPane;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.geometry.HPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.io.*;
public class AddUser extends Application {
private TextField tfUsername = new TextField();
private TextField tfPassword = new TextField();
private Button btAddUser = new Button("Add User");
private Button btClear = new Button("Clear");
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create UI
GridPane gridPane = new GridPane();
gridPane.setHgap(5);
gridPane.setVgap(5);
gridPane.add(new Label("Username:"), 0, 0);
gridPane.add(tfUsername, 1, 0);
gridPane.add(new Label("Password:"), 0, 1);
gridPane.add(tfPassword, 1, 1);
gridPane.add(btAddUser, 1, 3);
gridPane.add(btClear, 1, 3);
// Set properties for UI
gridPane.setAlignment(Pos.CENTER);
tfUsername.setAlignment(Pos.BOTTOM_RIGHT);
tfPassword.setAlignment(Pos.BOTTOM_RIGHT);
GridPane.setHalignment(btAddUser, HPos.LEFT);
GridPane.setHalignment(btClear, HPos.RIGHT);
// Process events
btAddUser.setOnAction(e -> writeNewUser());
btClear.setOnAction(e -> {
tfUsername.clear();
tfPassword.clear();
});
// Create a scene and place it in the stage
Scene scene = new Scene(gridPane, 300, 150);
primaryStage.setTitle("Add User"); // Set title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public void writeNewUser() {
PrintWriter fw = null;
try {
fw = new PrintWriter("users.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(tfUsername.getText());
bw.newLine();
bw.write(tfPassword.getText());
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
采纳答案by MadProgrammer
You're "original" had the fw.close
method within the catch
block of the try-catch
in your writeNewUser
method...
你是“原始的”在你的方法fw.close
的catch
块中拥有该方法......try-catch
writeNewUser
public void writeNewUser() {
PrintWriter fw = null;
try {
fw = new PrintWriter("users.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(tfUsername.getText());
bw.newLine();
bw.write(tfPassword.getText());
} catch (IOException e) {
e.printStackTrace();
fw.close();
}
}
As has been pointed out, this will only be called if something goes wrong. Also, PrintWriter#close
will throw an IOException
and fw
could be null
, causing more issues...
正如已经指出的那样,只有在出现问题时才会调用它。此外,PrintWriter#close
将抛出一个IOException
和fw
可能是null
,导致更多的问题......
The modified code is only marginally better...
修改后的代码只是稍微好一点......
public void writeNewUser() {
PrintWriter fw = null;
try {
//....
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Placing the close
call in within the try
section means that it will only be called if all goes well. If an exception occurs for some reason, the resource will never be closed
将close
调用放入该try
部分意味着只有在一切顺利的情况下才会调用它。如果由于某种原因发生异常,资源将永远不会被关闭
You should also be closing the outer resource, the BufferedWriter
in this case, this will chain the close call to each enclosing resource.
您还应该关闭外部资源,BufferedWriter
在这种情况下,这会将关闭调用链接到每个封闭资源。
Instead, you should use a try-with-resources
, which will close the resources automatically, for example...
相反,您应该使用 a try-with-resources
,它将自动关闭资源,例如...
public void writeNewUser() {
try (BufferedWriter bw = new BufferedWriter(new PrintWriter("users.txt"))) {
bw.write(tfUsername.getText());
bw.newLine();
bw.write(tfPassword.getText());
} catch (IOException e) {
e.printStackTrace();
}
}
Take a look at The try-with-resources Statementfor more details
查看try-with-resources 声明以了解更多详细信息
Updated
更新
To append to the file, you might need to use FileWriter
instead, for example...
要附加到文件,您可能需要FileWriter
改用,例如...
public void writeNewUser() {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("users.txt", true))) {
bw.write(tfUsername.getText());
bw.newLine();
bw.write(tfPassword.getText());
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
回答by JClassic
The problem is within the writeNewUser method:
问题出在 writeNewUser 方法中:
public void writeNewUser() {
PrintWriter fw = null;
try {
fw = new PrintWriter("users.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(tfUsername.getText());
bw.newLine();
bw.write(tfPassword.getText());
} catch (IOException e) {
e.printStackTrace();
fw.close();
}
}
The fw.close() is in the catch loop, but the problem is that it only closes when there is an error (thats why there is a catch block)
fw.close() 在 catch 循环中,但问题是它只在出现错误时关闭(这就是为什么有一个 catch 块)
The fix for this:
对此的修复:
public void writeNewUser() {
PrintWriter fw = null;
try {
fw = new PrintWriter("users.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(tfUsername.getText());
bw.newLine();
bw.write(tfPassword.getText());
fw.close();
} catch (IOException e) {
e.printStackTrace();
fw.close
}
}
^^put the fw.close() in the try and catch block.
^^ 将 fw.close() 放在 try 和 catch 块中。
As for making it repeatable, try saving the passwords and usernames (Using the scanner class) into an array before initializing the FileWriter, and then have a for
loop to rewrite the array into the file.
至于使其可重复,尝试在初始化 FileWriter 之前将密码和用户名(使用扫描仪类)保存到一个数组中,然后有一个for
循环将数组重写到文件中。
Hope this helps: Classic
希望这有帮助:经典