【问题标题】:How to implement code for writing in a text file (Java) [duplicate]如何实现用于写入文本文件的代码(Java)[重复]
【发布时间】:2018-05-19 21:53:37
【问题描述】:

我正在尝试弄清楚如何在我已经建立的代码中实现用于写入文本文件的代码(在第三方的主要帮助下,因为我是 Java 新手)。

我希望将已注册或创建的客户或预订的详细信息保存在文本文件中,如下所示(第一步 - 1)注册新客户,或 2)创建一个新的预订):

public static void main(String[] args) {

    // setup and initialise the test data
    List<Flight> availableFlights = generateTestFlights();
    List<Hotel> availableHotels = generateTestHotels();
    List<Excursion> availableExcursions = generateTestExcursions();

    // create a new list of bookings
    List<Booking> listOfReservedBookings = new ArrayList<>();

    // initialise a new sales consultant which will operate on the behalf of the
    // customer
    SalesConsultant salesConsultant = new SalesConsultant();

    // initialise the keyboard code
    Scanner scanner = new Scanner(System.in);

    // what will be displayed when executing application
    System.out.println("Menu: ");
    System.out.println("1) Register a new Customer");
    System.out.println("2) Create a new Booking");
    System.out.println("3) View available list of Flights");
    System.out.println("4) View available list of Hotels");
    System.out.println("5) View available list of Excursions");
    System.out.println("6) View Reserved Bookings");
    System.out.println("Please make your choice (type code number): ");

    // displaying above written within brackets
    String choice = scanner.nextLine();

    // when "exit" choice is not showing
    while (choice.equalsIgnoreCase("exit") == false) {

        // register customer
        if (choice.equalsIgnoreCase("1")) {
            System.out.println("Registering a new customer: ");

            // get the card ID for the new customer
            System.out.println("Please insert Customer ID Card Number: ");
            String cardID = scanner.nextLine();

            // get the name of the new customer
            System.out.println("Please insert Customer Name & Surname: ");
            String name = scanner.nextLine();

            // get the address of the new customer
            System.out.println("Please insert Customer Address: ");
            String address = scanner.nextLine();

            // register customer
            Customer customer = new Customer();
            salesConsultant.registerCustomer(customer);

            System.out.println("Customer has been registered successfully!");
        }

此外,我需要为此创建一个新类,还是可以通过 main 方法完成?

不确定是否需要更多代码。

有人可以就此提出建议吗?

非常感谢。

【问题讨论】:

  • 虽然不是强制性的,但如果您要将这些数据存储并检索到文本文件中,那么在我看来,是的,您应该创建另一个类来处理读取和写入文件等等.这种东西最适合数据库,因为在需要时检索特定于数据的查询要容易得多。

标签: java file text


【解决方案1】:

我建议对特定客户的操作使用Customer 方法和字段,这将封装所有客户共有的行为。你需要让Customer 类看起来像这样:

public class Customer {
    String cardID;
    String name;
    String address;

    public Customer(String cardID, String name, String address) {
        this.cardID = cardID;
        this.name = name;
        this.address = address;
    }
}

然后你可以在这个类里面创建一个方法saveToFile

public void saveToFile(String fileToWrite) {
    List<String> lines = Arrays.asList(cardID, name, address);
    Path file = Paths.get(fileToWrite);
    try {
        Files.write(file, lines);
    } catch (IOException ex) {
        System.err.println("Error writing to " + file);
    }
}

(有关创建和写入文本文件的其他方法,请参阅this question)。创建此方法后,在您的main 方法中使用它:

// register customer                
Customer customer = new Customer(cardID, name, address);
customer.saveToFile(cardID + ".txt");

这里,通过上面所示的非默认构造函数创建了一个客户(实际上现在默认的已经不存在了),并以客户的cardID定义的名称保存到当前目录下的文件中(以区分不同客户对应的文件,你可以随意更改命名方案。

顺便问一下,您真的要将此类应用程序的所有记录保存在文本文件中吗?通常,数据库用于此类目的,因为它更方便、更安全。

【讨论】:

  • 谢谢大家的帮助,我会看看你们提供了什么。非常感谢。
【解决方案2】:

您正在寻找的是Java 中的文件处理。你可以很容易地在网上查到它。
无论如何,
您已经在使用 System.out.println()scanner.nextLine() 进行 I/O,其中

System 是一个 Java 类。
out 是 System 类的成员。
println 是方法。

这些用于从/向控制台读取/写入变量。

与从文件中读取/写入类似,您需要使用 FileWriterFileReaderFileInputStream,FileOutputStream 类,具体取决于您要处理的内容,二进制数据或 ASCII 文本。

这里有一些参考资料供你学习:

GeeksforGeeks File Handling in Java
File Handling writing objects

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 2016-07-20
    • 2013-07-21
    相关资源
    最近更新 更多