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

标签 java printing

我想编写存储有关汽车信息的程序。例如,您可以在对话框中输入每辆车的品牌和所有者名称。最后,应通过将信息写入文本文件然后从文本文件中读取到对话框来显示包含所有汽车信息的对话框。我创建了一个 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/

相关文章:

java - 发布到 Play 商店时支持的设备为零

c# - Process.Startinfo 从 ASP.NET 打印 PDF 在 Windows Server 2003 中不起作用

打印用户输入的字符串变量需要 Java 帮助

java - 静态数据使用SoftReference防止Java内存不足

asp.net - html 中的页面设置信息或由 asp.net 创建的页面

printing - 将自定义页面大小添加到.ppd的最简单方法是什么?

javascript - 尝试使用 getElementById 在 Javascript 中打印正确答案

java - 如何在 java 中使用 yarn api 提交 mapreduce 作业

java - 是否可以使用 Orika Mapper 将字段从两个源对象映射到目标对象?

java - 我在线程 "main"org.testng.TestNGException : Cannot load class from file while running a test 中收到错误 Exception