将对话框中的信息存储到Java文本文件
我想写一个程序来存储关于汽车的信息。例如,在对话框中输入每辆车的品牌和车主姓名。最后,应通过将信息写入文本文件,然后将其读取到对话框中来显示包含所有汽车信息的对话框。我创建了一个方法getInfo,它正确地显示了相应的框将对话框中的信息存储到Java文本文件,java,printing,Java,Printing,我想写一个程序来存储关于汽车的信息。例如,在对话框中输入每辆车的品牌和车主姓名。最后,应通过将信息写入文本文件,然后将其读取到对话框中来显示包含所有汽车信息的对话框。我创建了一个方法getInfo,它正确地显示了相应的框 public static void getInfo() { boolean done = false; do { String brand=JOptionPane.showInputDialog(null, "Brand?"); String na
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);
}
}
我缺少什么以及如何实现功能?您可以在循环外部定义一个
缓冲写入程序
:
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;
做:
退出循环后,调用:
bw.close();
首先,对于每个循环,您都要创建一个新的
info
实例,因此您将丢失以前运行的信息
在main方法中,您正在访问信息
,但在该范围内不应该知道它。您可以做的是从getInfo()
方法返回info
然后,您还应该考虑换行等问题,但第一次尝试时,应该是这样。尝试以下方法:
public static void main() {
boolean done = false;
do {
Info info = getInfo();
storeInfo(info);
done = getDone();
} while (!done);
displayInfo();
}
class Info {
private brand;
private owner;
}
现在,您可以在每个方法中执行单个操作
getInfo调用showInputDialog并返回一个信息对象
storeInfo将信息对象存储到文本文件中
如果用户想要退出,getDone调用showInputDialog并返回
displayInfo打开文本文件并显示信息
实现displayInfo的最简单方法可能是:
void displayInfo() {
// Create a window with TextBox
// Open the text file
// Read the content of the text file and add it to the TextBox
}
你让它工作了吗?我得到一个文件错误:java.io.IOException:没有这样的文件或目录。我是否应该使用实际位置而不是“path/to/the/file.txt”?@user30523是。当然如果您的计算机上不存在路径
path/to/the/file.txt
,则会出现错误。您需要提供一个可以存在的文件的路径。(如果没有,那么代码将创建它)。例如(在Windows上):“C:\\Users\\\\Desktop\\output.txt”
。现在它可以工作了!但是,只有一辆(最新)输入的汽车的信息会打印到文本文件中,如何防止覆盖?我添加了displayInfo的结构。你不需要真正的代码,是吗?
void displayInfo() {
// Create a window with TextBox
// Open the text file
// Read the content of the text file and add it to the TextBox
}