【问题标题】:Reading a customers name in a txt file with File Reader使用文件阅读器读取 txt 文件中的客户姓名
【发布时间】:2012-03-06 17:31:26
【问题描述】:

我的问题是我不知道如何使用文件阅读器读取客户姓名。

我正在制作预订系统,我需要知道客户已经存在。这就是为什么我必须阅读我的 Customers.txt 文件以便检查某人是否已经是客户的原因。如果他不是,我会用文件编写器制作一个新的(我已经有了代码)。

这个预约系统的意思是和理发师预约。我必须将预订放在另一个名为 Reservations.txt 的 txt 文件中,在该文件中您可以看到每个预订时间以及谁进行了预订。

感谢您的帮助!

这是我已有的代码: (有些 cmets 是荷兰语,但我会翻译)

package nielbutaye;
import java.io.*;
import java.util.UUID;
/**
 * @author Niel
 *
 */
public class Klant {
    //declaration that represents the text
    public static String S;

    public static String NEWLINE = System.getProperty("line.separator");

/**
 * constructor
 */
public Klant(){}

/**
 * @return
 * By giving the name of the customer you will get all the data from  the customer
 */
public double getCustomer() {


    return 0 ;
}

/**
 * Make a new customer
 */

public void setNew customer(){
    // make a newSimpleInOutDialog     
    SimpleInOutDialog  input = new SimpleInOutDialog("A new customer");
    //input
    S = "Name customer: " + input.readString("Give in your name:");
    WriteToFile();
    S = "Adress: " + input.readString("Give your adress");
    WriteToFile();
    S = "Telephonenummber: " + input.readString("Give your telephonenumber");
    WriteToFile();
    //making a customerID
      UUID idCustomer = UUID.randomUUID();  
    S = "CustomerID: " + customerID.toString();
    WriteToFile();

}

public void WriteToFile(){
try{

    FileWriter writer = new FileWriter("L:\\Documents/Informatica/6de jaar/GIP/Customer.txt", true);
    BufferedWriter out = new BufferedWriter(writer);
    //Wrting away your data
    out.write(S + NEWLINE);
    //Closing the writer
    out.close();


}catch (Exception e){//Catch when there are errors
    System.err.println("Error: " + e.getMessage());
    }
    }
}

【问题讨论】:

  • 你能发布你到目前为止的代码吗?
  • @hmjd ,更新了问题(:
  • 来自 JavaScript 标记工具提示:“...它 [JavaScript] 与 Java 不同。”

标签: java filereader filewriter


【解决方案1】:

BufferedReader() 有一个名为 readLine() 的方法,您可以使用它从文件中读取一行:

BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;

while ((line = br.readLine()) != null)
{
    ...
}

br.close();

从您的WriteToFile() 方法看来,客户的详细信息占据了四行,客户的姓名出现在第一行。搜索客户时,安排while 循环仅检查每读取的第四行。

其他要点:

  • 似乎没有理由让S 成为成员变量,更不用说static。只需在 setNewCustomer() 中声明一个本地 String 实例并将其作为参数传递给 WriteToFile()
  • 您可以使用BufferedWriternewLine() 方法来代替定义NEWLINE 变量。

【讨论】:

  • 好的,谢谢你的回复,你能告诉我把BufferedWriter的newLine()方法放在代码的什么地方吗,因为我不知道......
  • out.write(S); out.newLine();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
相关资源
最近更新 更多