我正在研究的这个项目,这里是将数据写入文件的函数:
public void writetofile(){
String bucky[]={custname,custlname,agee,address,id};
for(int i = 0; i < bucky.length; i++) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("records.txt", true))) {
String s;
s = bucky[i];
bw.write(s);
bw.newLine();
bw.flush();
}
catch(IOException ex) {
JOptionPane.showMessageDialog(null, "Error In File");
}
}
};
并且定义了另一个从文件中读取数据的函数
public void filereader (){
int i=0;
Object[] options = {"OK"};
try
{
FileInputStream in = new FileInputStream("records.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
StringBuffer sb = new StringBuffer();
while((strLine = br.readLine())!= null)
{
sb.append(strLine +"\n");
}
JOptionPane.showMessageDialog( null, sb.toString());
}catch(Exception e){
JOptionPane.showOptionDialog(null, "Error", "Customers", JOptionPane.PLAIN_MESSAGE,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
}
};
问题是,假设我想在我的项目中为客户创建一个帐户,所以很少问到诸如姓名,姓氏,性别等问题,所有这些信息都已保存,但是当我尝试读取文件所有数据都将以无格式显示,我希望它们以正确的方式显示:
customer name : Michelle ,
gender : Female ;
但是现在它看起来像这样:
michelle ,
female ,
答案 0 :(得分:1)
您可以先构建所需的输出,然后只调用bw.write(s);
或遵循R.J的建议。将所有内容放入对象并覆盖该类的toString
methid。这将是解决问题的最佳方式
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
public class Customer
{
private final String firstName;
private final String lastName;
private final String address;
private final int age;
private final int id;
public Customer(String firstName, String lastName, String address, int age,
int id)
{
super();
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.age = age;
this.id = id;
}
@Override
public String toString ()
{
return "Customer [firstName=" + firstName + ", lastName=" + lastName
+ ", address=" + address + ", age=" + age + "]";
}
public static void main (String[] args)
{
}
public void writetofile (String custname, String custlname, int agee,
String address, int age)
{
Customer customer = new Customer(custname, custlname, address, age, id);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(
"records.txt", true)))
{
String s = customer.toString();
bw.write(s);
bw.newLine();
bw.flush();
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(null, "Error In File");
}
}
}