使用RandomAccessFile建立用户注册表(user.txt)

目录

前言

一、用户信息写入文件

二、文件内容的读出


前言

内容需要有:

姓名,年龄,密码,昵称

一、用户信息写入文件

public static void main(String[] args) throws IOException {
		File f=new File("user.txt");
		f.createNewFile();
		//用户输入数据
		Scanner scan=new Scanner(System.in);
		RandomAccessFile raf = new RandomAccessFile(f, "rw");
		raf.seek(raf.length());
		System.out.println("请输入姓名:");
		String name=scan.nextLine();
		System.out.println("请输入密码:");
		String psw=scan.nextLine();
		System.out.println("请输入昵称:");
		String nichen=scan.nextLine();
		System.out.println("请输入年龄:");
		String age=scan.nextLine();
		
		//将用户数据写入user.txt
		byte[] bs =name.getBytes("utf-8");
		//将数组扩容至32字节,方便写入与读取
		bs=Arrays.copyOf(bs, 32);
		raf.write(bs);
		bs = psw.getBytes("utf-8");
		bs=Arrays.copyOf(bs, 32);
		raf.write(bs);
		bs = nichen.getBytes("utf-8");
		bs=Arrays.copyOf(bs, 32);
		raf.write(bs);
		bs = age.getBytes("utf-8");
		bs=Arrays.copyOf(bs, 32);
		raf.write(bs);
		scan.close();
		raf.close();
	}

 

 

二、文件内容的读出

public static void main(String[] args) throws Exception {
		Scanner scan =new Scanner(System.in);
		System.out.println("请输入需要修改的账号名称:");
		String upname=scan.nextLine();
		RandomAccessFile raf=new RandomAccessFile("user.txt", "rw");
		byte[] bs=new byte[32];
		boolean index=false;
		for(int i=0;i<raf.length()/128;i++) {
			raf.seek(i*128);//指针每次需要移动至下一条记录的位置
			raf.read(bs);
			String str=new String(bs,"utf-8").trim();
			if(upname.equals(str)) {
				System.out.println("请输入修改后的昵称:");
				bs=scan.nextLine().getBytes("utf-8");
				raf.seek(i*128+64);
				raf.write(bs);
				System.out.println("修改成功!");
				index=true;
			}
		}
		if (!index) {
			System.out.println("用戶不存在!!");
		}
		raf.close();
		scan.close();
	}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值