gpt4 book ai didi

java - 将对话框中的信息存储到文本文件 Java

转载 作者:行者123 更新时间:2023-11-30 06:38:48 25 4
gpt4 key购买 nike

我想编写存储有关汽车信息的程序。例如,您可以在对话框中输入每辆车的品牌和所有者名称。最后,应通过将信息写入文本文件然后从文本文件中读取到对话框来显示包含所有汽车信息的对话框。我创建了一个 getInfo 方法,它可以正确显示相应的框。

public static void getInfo() {
boolean done = false;
do {
String brand=JOptionPane.showInputDialog(null, "Brand?");
String name=JOptionPane.showInputDialog(null, "Owner?");

if (brand == null) {
done = true;

} else {
String info ="Car: "+brand+" "+"\nOwner: "+name;
String message = " Do you want to input more cars?";
int buttonClicked = JOptionPane.showConfirmDialog(null, message, "", JOptionPane.YES_NO_OPTION);
done = (buttonClicked == JOptionPane.NO_OPTION);

}
} while (!done);
}

public static void main(String[] args) {
getInfo();
}

我不确定如何将信息添加到文本文件以及如何处理循环。为了将信息写入文本文件,我尝试将 main 方法更改为以下

public static void main(String[] args) throws IOException {

try (PrintWriter outstream = new PrintWriter
(new BufferedWriter
(new FileWriter("cars.txt", true)))) {
getInfo();
outstream.println(info);
}
}

我缺少什么以及如何实现该功能?

最佳答案

您可以在循环之外定义一个BufferedWriter:

File outputFile = new File("path/to/the/file.txt");
if(!outputFile.exists()){
try {
outputFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedWriter bw = null; //this declares a buffer that writes to some stream.
try{
bw = new BufferedWriter(new FileWriter(outputFile,true)); //here we actually create it, and tell it to write to a file stream, directed at the outputFile file.
}catch(IOException e){
e.printStackTrace(); //this is if the file doesn't exist, which shouldn't happen, but we still need to put this here, because better safe than sorry.
}

然后在你的循环中:在

之后
String info ="Car: "+brand+" "+"\nOwner: "+name;

做:

String info ="Car: "+brand+" "+"\nOwner: "+name;


try {
bw.write(info);//write the information to the buffer when there's new info.
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}

退出循环后,调用:

bw.close(); 

关于java - 将对话框中的信息存储到文本文件 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44760994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com