简体   繁体   English

Java中的Scanner是否足以读取文本文件中的输入?

[英]is Scanner in Java enough for reading input from a text file?

what i'm going to do 我要做什么

i'm going to build a phone book program in Java to do the following jobs: 我将用Java构建电话簿程序来完成以下工作:

  1. read from two text files, instruction.txt and phonebook.txt 从两个文本文件中读取, instruction.txtphonebook.txt
  2. phonebook.txt includes some phone entry, each entry for a person phonebook.txt包含一些电话条目,每个条目代表一个人
  3. instruction.txt includes some instructions i would execute to phonebook.txt , such as add new entry, query an entry, delete an entry, etc. Instruction.txt包含一些我将要执行到phonebook.txt的指令,例如添加新条目,查询条目,删除条目等。
  4. for sure i would care about the output of my program, but for now, i focus on the input. 当然,我会关心程序的输出,但是现在,我专注于输入。

my problem 我的问题

i want to use Scanner to do all the input jobs, read in all the strings stored in instruction.txt and phonebook.txt, but i doubt if i can handle all the difficult conditions. 我想使用Scanner进行所有输入工作,读取存储在struction.txt和phonebook.txt中的所有字符串,但是我怀疑我是否可以处理所有困难的条件。 Conditions like how to correctly get each entry, and identify what it is. 条件包括如何正确获取每个条目并确定其含义。

for each phone book entry, five fields are needed: name , birthday , phone number , address , email . 对于每个电话簿条目,都需要五个字段: 姓名生日电话号码地址电子邮件 And name and birthday are compulsory for each entry. 每个条目都必须有姓名生日

for instructions, they are add , delete , save , read , query . 对于说明,它们是添加删除保存读取查询

sample text files 样本文本文件

here is a sample of instruction.txt : 这里是instruction.txt的一个示例:

add name Testing Three; 添加名称测试三; birthday 13-05-1982; 生日13-05-1982; phone 12345677; 电话12345677; address Address Three; 地址地址三; email testing@gmail.com delete Testing One save 电子邮件testing@gmail.com删除测试一保存

each entry is separated by one or more blank lines. 每个条目都由一个或多个空行分隔。 here is a sample of phonebook.txt : 这是phonebook.txt的示例:

name Testing One 名称测试一

birthday 13-05-1980 生日13-05-1980

phone 12345678 电话12345678

address Address One 地址地址一

email testing1@gmail.com 电子邮件testing1@gmail.com

-----------this is a blank line ------------------------- -----------这是一个空白行-------------------------

name Testing Two 名称测试二

birthday 13-05-1981 生日13-05-1981

phone 12345644 电话12345644

address Address Two 地址地址二

email testing2@gmail.com 电子邮件testing2@gmail.com

Yes, Scanner is sufficient to do the reading, though you'd need to use it the right way. 是的,尽管您需要以正确的方式使用它,但Scanner足以进行阅读。

Getting the entries is simply a matter of calling a Scanner.next... method, and you can deal with the optional fields using hasNext... . 只需通过调用Scanner.next...方法即可获取条目,并且可以使用hasNext...处理可选字段。

(Hint: use one scanner to split into lines, and then a new scanner to split each line.) (提示:使用一台扫描仪将其分成几行,然后使用新扫描仪将每一行分开。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM