java - 无法将输入从 JTextField 存储到文件写入器
问题描述
我正在尝试创建一个电话目录,用户必须在其中使用 JTextField 输入多个输入。我还有一个搜索选项,可以从文件写入器的目录中搜索输入的名称,但我似乎无法将我的输入存储在文件写入器中。这是我的初始代码
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int menu = 0;
boolean quit = false;
do{
String input = JOptionPane.showInputDialog(null,"Telephone Directory Management System"
+ "\n1. Add a Student"
+ "\n2. Search"
+ "\n3. Sort Data"
+ "\n4. List of all data"
+ "\n5. Exit"
+ "\n\nPlease enter your choice:","Main Menu",JOptionPane.QUESTION_MESSAGE);
menu = Integer.parseInt(input);
switch (menu) {
case 1:
JTextField student = new JTextField();
JTextField name = new JTextField();
JTextField address = new JTextField();
JTextField phone = new JTextField();
Object[] fields = {
"Enter Student ID:",student,
"Enter Name:",name,
"Enter Address:",address,
"Enter Phone No.:",phone};
int add = JOptionPane.showConfirmDialog(null,fields,"Add a Student",JOptionPane.OK_CANCEL_OPTION);
if (add == JOptionPane.OK_OPTION)
{
String student1 = student.getText();
String name1 = name.getText();
String address1 = address.getText();
String phone1 = phone.getText();
FileWriter fw = new FileWriter(new File("directory.txt"), true);
BufferedWriter out = new BufferedWriter(fw);
out.write(student1 + " " + name1 + " " + address1 + " " + phone1);
out.newLine();
}
break;
case 2:
input = JOptionPane.showInputDialog(null,"Enter name to search information:","Search",JOptionPane.OK_CANCEL_OPTION);
File f = new File("directory.txt");
try {
BufferedReader freader = new BufferedReader(new FileReader(f));
String s;
while ((s = freader.readLine()) != null) {
String[] st = s.split(" ");
String id = st[0];
String nm = st[1];
String add1 = st[2];
String phoneNo = st[3];
if (input.equals(nm)) {
JOptionPane.showMessageDialog(null,"Student ID: "+id+"\nName: "+nm+"\nAddress: "+add1+"\nPhone No.: "+phoneNo+"","Information",JOptionPane.QUESTION_MESSAGE);
}
}
freader.close();
} catch (Exception e) {
}
break;
我之前尝试过使用扫描仪,它确实存储了我的输入,但我需要在这个中使用 JOptionPane。非常感谢任何可以帮助我的人。
解决方案
您应该在写入 BufferedWriter 后关闭它,就像这样
out.close()
如果您不这样做,则 BufferedWriter 不会将您写入其中的内容刷新到底层流中。
推荐阅读
- c# - 尝试在 Unity 3D 中创建进入球体的对象变换列表
- c++ - 在opengl中将二维纹理应用于具有z方向变化的单个立方体面
- javascript - 我想学javascript
- javascript - 如何在表格正方形中制作单元格
- material-ui - Material UI 的 Snackbar 没有向下滑动
- nativescript - 带有 vue 和 ts 的 Nativescript 无法构建
- javascript - Node.js 引用错误 - ReferenceError:前缀操作中的左侧表达式无效
- haskell - 当非单子值变成单子值时正确重构 Haskell 代码
- node.js - 需要 CLIENTID 的 OAuth2Strategy 出错
- angular6 - 如何以角度使用 MapMyIndia API?