【发布时间】:2019-04-21 01:18:31
【问题描述】:
我的节目是关于联系人的。 例如,当医生插入姓名,姓氏,电话时,每次他想将数据保存到 txt 文件中时,输出将是:
somename
somesurname
sometelephone
somename
somesurname
sometelephone
...
现在我做了输出将只有一行:
somename somesurname sometelephone 你可以在代码中看到:
if(text.equals("Save")) {
try {
ArrayList<String> contactsinformations=new ArrayList<>();
String name=tname.getText();
String surname=tsurname.getText();
String telephone=ttelephone.getText();
contactsinformations.add(0,name+" ");
contactsinformations.add(1,surname+" ");
contactsinformations.add(2,telephone+" ");
FileWriter outFile = new FileWriter("Contacts.txt");
BufferedWriter outStream = new BufferedWriter(outFile);
for(int i=0; i<contactsinformations.size(); i++)
outStream.write(String.valueOf(contactsinformations.get(i)));
outStream.close();
JOptionPane.showMessageDialog(this,"Data saved.");
} catch(IOException e) {
System.out.println("ERROR IN FILE");
}
}
我使用 for 循环来获取 ArrayList 的大小,但试图弄清楚如何在不同的行中插入信息。
警告:已更新问题! 问题解决了!
if(text.equals("Save")) {
try
{
ArrayList<String> contactsinformations=new ArrayList<>();
contactsinformations.add(tname.getText());
contactsinformations.add(tsurname.getText());
contactsinformations.add(ttelephone.getText());
FileWriter outFile = new FileWriter("Contacts.txt",true);
BufferedWriter outStream = new BufferedWriter(outFile);
for (int i = 0; i < contactsinformations.size(); i++) {
outStream.write(contactsinformations.get(i));
outStream.newLine();
}
JOptionPane.showMessageDialog(this,"Data saved.");
outStream.close();
}
【问题讨论】:
-
contactsinformations是ArrayList<String>所以它的get方法已经返回字符串。用String.valueOf包裹它有什么意义? -
BTW 每次调用
new FileWriter("Contacts.txt")时都会清除使用文件的内容。如果您想将文本附加到现有文件而不清除它,请查看How to add a new line of text to an existing file in Java? -
你也可以用
PrintWriter包裹BufferedWriter,它有println方法。例如PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Contacts.txt", true))); -
@Pshemo 在
PrintWriter pw = new PrintWriter(new FileWriter("Contacts.txt"));之间不需要BufferedWriter 有效 -
@azro 是的,如果我们不需要 BufferedWriter 提供的缓冲。从我在source code of PrintWriter 看到的情况来看,它仅在处理
OutputStream或File file或String file时自动添加BufferedWriter,但在处理其他Writer时不会自动添加(尽管对于这种情况,缓冲可能仍由其他我没有注意到的方式)。