本帖最后由 zhou_m_j 于 2016-11-27 16:59 编辑
[Java] 纯文本查看 复制代码 import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
static Scanner in =new Scanner(System.in);
static String fileName = new String("H:\\user.txt");
public static void menu(){
//菜单
System.out.println("\n1.查看用户");
System.out.println("2.注册");
System.out.println("3.退出");
System.out.print("请输入1-3之间的数:");
}
public static void getInfo(List<String> user){
//从文件中读取用户
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(fileName);
br = new BufferedReader(fr);
while(true){
String tmpStr = br.readLine();
if(null == tmpStr){
//判断是否读到文件末尾
break;
}
user.add(tmpStr);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
//关闭文件流
try {
if(fr!=null)
fr.close();
if(br!=null)
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void printToConsolo(List<String> user){
//查看用户模块
for(String str:user){
//分割用户名和密码,只输出用户名
String []str1 = str.split("-");
System.out.println(str1[0]);
}
}
public static void register(List<String> user){
//注册模块
while(true){
System.out.print("请输入用户名:");
Scanner in =new Scanner(System.in);
String userName = in.nextLine();
boolean flag = true;
for(String str:user){
//查询是否重名
String []str1 = str.split("-");//分割用户名和密码
if(str1[0].equals(userName)){
flag = false;
break;
}
}
if(flag){
//不重名
System.out.print("请输入密码:");
String userPassword = in.nextLine();
//把新用户放入到user列表中
user.add(userName+"-"+userPassword);
BufferedWriter out = null;
try {
//新用户写入文件
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName,true)));
out.write(user.get(user.size()-1)+"\r\n"); //注意换行位置
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
//关闭文件流
if(out!=null)
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("注册成功");
break;
}
else
//重名
System.out.println("用户名已存在!");
}
}
public static void main(String[] args) {
List<String> user = new ArrayList<String>();
getInfo(user);
while(true){
menu();
int num = in.nextInt();
if(num>3||num<1)
//输入数据是否合法
continue;
else if(num != 3){
if(num == 1){
//输入1,打印
printToConsolo(user);
}
else{
//输入2,注册
register(user);
}
}
else
//输入3
return;
}
}
}
仅供参考,有问题可以继续问 |