尝试创建文件

时间:2013-07-12 13:58:58

标签: java file file-io filereader filewriter

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

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

3 个答案:

答案 0 :(得分:0)

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

openInputFile()
// write data.....
closeInputFile();

答案 1 :(得分:0)

write对象为null时,您似乎正在尝试写入文件。您先致电write.printf,然后在致电openInputFile()之后再将其初始化。

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

答案 2 :(得分: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()方法。