0

我想创建一个文本文件来存储数据。文本文件的名称取决于用户键入的内容。该代码工作正常,但我不知道为什么,它创建文件,但它也会自动生成一个空文件,但我的数据不在这两个文件中。为什么?这是我的代码:

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);
    }
}
4

3 回答 3

0

您首先写入未打开的文件

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();

您可能应该在类外的某个地方调用 openInputFile(),然后再调用 addCustomer() 方法。

于 2013-07-12T14:04:46.227 回答
0

您还需要添加对 close 方法的调用,否则数据将不会写入文件并确保在写入时按顺序完成

openInputFile()
// write data.....
closeInputFile();
于 2013-07-12T14:02:33.523 回答
0

当您的write对象是null. 您write.printf先调用,然后在调用后对其进行初始化openInputFile()

此外,正如 Java Devil 所提到的,您忽略了关闭PrintWriter.

于 2013-07-12T14:04:11.233 回答