java用户输入判断保存到文件中(会覆盖原数据)

来源:互联网 发布:淘宝闲鱼app下载 编辑:程序博客网 时间:2024/05/22 18:11
主函数
package com.java.io;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;public class TestInPut {private static Person person;public static void main(String[] args) {TestInPut.timeType();}public static void timeType(){//实现循环多次输入,多数据保存while(true){Person p=TestInPut.typeIn();person=p;String sTypeWr=person.getName()+"-"+person.getPsd();TestInPut.typeWriter(sTypeWr);BufferedReader br =new BufferedReader(new InputStreamReader(System.in));try {System.out.println("是否继续输入信息,退出请输入“exit”");String brs=br.readLine();//Integer cs=Integer.valueOf(brs);if(brs.equalsIgnoreCase("exit")){break;}else{}//br.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} }}public static void typeWriter(String str){OutputStream os= null;//输出字节流OutputStreamWriter ops=null;//处理流BufferedWriter bw=null;//字符转化流String path="D:\\testio\\a\\a.txt";//文件路径File f1= new File(path);//文件对象生成if(!f1.exists()){//判断文件是否存在f1.getParentFile().mkdirs();//不存在创建文件}try {os= new FileOutputStream(f1);ops=new OutputStreamWriter(os); bw= new BufferedWriter(ops);bw.write(str);//写入数据System.out.println(str);bw.newLine();bw.flush();//将缓冲区的字符数据写到文件里/*ops.close();bw.close();*/} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static Person typeIn(){System.out.println("****************");//定义一个输入字符流,套一个缓冲流BufferedReader br =new BufferedReader(new InputStreamReader(System.in));try {while(true){String str=br.readLine();//定义一个由英文和一个空格加上若干个英文的正则表达式String strR="^([a-zA-Z0-9]*\\s+[a-zA-Z0-9]*)$";//验证输入的字符串是否满足strR表达式的要求if(str.matches(strR)){String[] spR=str.split("\\s");//System.out.println(spR[0]+"---"+spR[1]);//System.out.println(str);Person personL =new Person();//写一个Person对象personL.setName(spR[0]);//将值传递给对象personL.setPsd(spR[1]);//将值传递给对象return personL;//将封装好的数据返回到对象中}else{System.out.println("wrong");}}//System.out.println("str");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}}
Person类
package com.java.io;public class Person {private String name;private String psd;public Person() {super();}public Person(String name, String psd) {super();this.name = name;this.psd = psd;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPsd() {return psd;}public void setPsd(String psd) {this.psd = psd;}}
控制台输出结果:

0 0
原创粉丝点击