/**
* 使用异常捕获机制完成下述IO操作
* 编写程序,要求下面的类实现功能:
* 添加新员工
* 要求用户输入一个员工信息,格式如下:
* jackson,25,男,5000,2008-12-22
* 用户输入后需要做下述验证:
* 要求用户名长度在1-20个字符之间且必须是英文
* 年龄在0-100之间的整数
* 性别只能是:"男"或"女"
* 当发现用户输入有不符合规定时,提醒用户
* 相关内容输入不符合要求,并要求重新输入。
* 都输入正确后,将该员工添加到emp.txt文件
* 的最后一行。
*/
代码如下:
public class Test006 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try{
for(;;){
System.out.println("请输入员工信息:");
String input = scan.nextLine();
String[] info = input.split(",");
if(!checkName(info[0])){
System.out.println("要求用户名长度在1-20个字符之间且必须是英文");
continue;
}
if(!checkAge(info[1])){
System.out.println("年龄在0-100之间的整数");
continue;
}
if(!checkGender(info[2])){
System.out.println("性别只能是:\"男\"或\"女\"");
continue;
}
String name = info[0];
int age = Integer.parseInt(info[1]);
String gender = info[2];
int salary = Integer.parseInt(info[3]);
Emp emp = new Emp(name,age,gender,salary,parseDate(info[4]));
//写入文件最后一行(UTF-8)
writeFile(emp);
System.out.println("文件写入完毕!");
break;
}
}catch(Exception e){
e.printStackTrace();
}
}
//将Emp写入文件
public static void writeFile(Emp emp) throws FileNotFoundException, UnsupportedEncodingException{
PrintWriter pw = null;
try{
FileOutputStream fos = new FileOutputStream("src/homework03/emp.txt",true);
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
pw = new PrintWriter(osw);
pw.println(emp.toString());
}finally{
pw.close();
}
}
//字符串转换为Date类型
public static Date parseDate(String date) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(date);
}
//性别只能是:"男"或"女"
public static boolean checkGender(String gender){
String regex = "[男女]";
return gender.matches(regex);
}
//年龄在0-100之间的整数
public static boolean checkAge(String age){
int num = Integer.parseInt(age);
return (num>0 && num<100);
}
//要求用户名长度在1-20个字符之间且必须是英文
public static boolean checkName(String name){
String regex = "[a-zA-Z]{1,20}";
return name.matches(regex);
}
}
测试结果如下:
请输入员工信息:
jackson,25,男,5000,2008-12-22
文件写入完毕!
代码如下:
public class TestWriter {
public static void main(String[] args) {
BufferedReader br = null;
try{
FileInputStream fis = new FileInputStream("src/homework03/emp.txt");
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
br = new BufferedReader(isr);
String str = null;
while( (str = br.readLine())!= null ){
System.out.println(str);
}
System.out.println("**********读取文件完毕*********");
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭流
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}