我想创建一个文本文件来存储数据。文本文件的名称取决于用户键入的内容。该代码工作正常,但我不知道为什么,它创建文件,但它也会自动生成一个空文件,但我的数据不在这两个文件中。为什么?这是我的代码:
public void setCustomerID()
{
System.out.print("\nYou've choose to register a new customer\n");
System.out.print("Please enter the customer's ID: ");
custID = input.nextLine();
}
public String getCustomerID()
{
return custID;
}
public void openInputFile()
{
try
{
write = new PrintWriter(new BufferedWriter(new FileWriter("C:\\RetailDatabase\\" + (getCustomerID()) + ".txt",true)));
}
catch(IOException e)
{
System.err.println("Error opening / creating / writing a file!");
}
}
public void addCustomer()
{
String firstname, lastname, sex, addrss, phoneNum, dob;
CustomerDetails record;
try
{
setCustomerID();
System.out.print("Please enter the customer's first name: ");
firstname = input.nextLine();
System.out.print("Please enter the customer's last name: ");
lastname = input.nextLine();
System.out.print("Please enter the customer's gender: ");
sex = input.nextLine();
System.out.print("Please enter the customer's address: ");
addrss = input.nextLine();
System.out.print("Please enter the customer's phone number: ");
phoneNum = input.nextLine();
System.out.print("Please enter the customer's date of birth (DD/MM/YYYY): ");
dob = input.nextLine();
record = new CustomerDetails(firstname, lastname, sex, addrss, phoneNum, dob);
write.printf("\nFirst Name: %s \nLast Name: %s \nGender: %s \nAddress: %s \nPhone Number: %s \nDate Of Birth: %s",record.getFirstName(),record.getLastName(),record.getGender(),
record.getCustAddress(),record.getPhoneNumber(),record.getDateOfBirth());
openInputFile();
System.out.print("Customer's details is recorded!");
}
catch(Exception e)
{
System.err.println("Error writing to file!");
return;
}
}
public void closeInputFile()
{
try
{
write.close();
}
catch(Exception e)
{
System.err.println("Error closing file!");
System.exit(1);
}
}