正在将text字段输入写入文件



我正试图从几个文本字段中获取输入,并在按下按钮时将它们作为列表添加到我的股票文件中。当我测试它时,它只是清空了我的库存文件。

JButton btnAddProduct = new JButton("Add Product");
btnAddProduct.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text0 = textbarcode.getText();
String text1 = textdeviceName.getText();
String text2 = textdeviceType.getText();
String text3 = textbrand.getText();
String text4 = textcolour.getText();
String text5 = textconnectivity.getText();
String text6 = textquantity.getText();
String text7 = textoriginalCost.getText();
String text8 = textretailPrice.getText();
String text9 = textadditionalInformation.getText();
textbarcode.setText("");
textdeviceName.setText("");
textdeviceType.setText("");
textbrand.setText("");
textcolour.setText("");
textconnectivity.setText("");
textquantity.setText("");
textoriginalCost.setText("");
textretailPrice.setText("");
textadditionalInformation.setText("");

String text = (text0 + text1 + text2 + text3 + text4 + text5 + text6 + text7 + text8 + text9);

try {
new BufferedWriter(new FileWriter("Stock.txt")).write(text);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}

});
btnAddProduct.setBounds(720, 367, 200, 37);
panelAddProduct.add(btnAddProduct);

问题是每次创建new FileWriter("Stock.txt")时都是在创建新文件或覆盖现有文件。

要解决这个问题,请使用new FileWriter("Stock.txt", true),使其看起来像这样:

new BufferedWriter(new FileWriter("Stock.txt", true)).write(text);

另外,使用close()方法关闭BufferedWriter。因此,在编写之后将new BufferedWriter()对象分配给close()的变量可能是一个更好的主意。

希望能解决问题:D

最新更新