流的注册和读取

完成用户注册功能

  • 用user.dat文件保存用户信息
  • 每个用户的信息包括:用户名,密码,昵称,年龄
  • 其中年龄是int值,其余都是字符串.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Test1 {
public static void main(String[] args) throws IOException {
RandomAccessFile raf
= new RandomAccessFile("user.dat","rw");
//先将指针移动到文件末尾,以便追加新记录
raf.seek(raf.length());

String name = "测试";
String password = "123456";
String nickname = "测";
int age = 18;
/*
* 每条记录占用100字节,其中用户名,密码,
* 昵称各占32字节,int型的age占4字节.
* 数据"留白"的目的是便于后期修改信息.
*/
//写用户名
byte[] data = name.getBytes("UTF-8");
data = Arrays.copyOf(data, 32);
raf.write(data);//一次写了32字节

data = password.getBytes("UTF-8");
data = Arrays.copyOf(data, 32);
raf.write(data);

data = nickname.getBytes("UTF-8");
data = Arrays.copyOf(data, 32);
raf.write(data);

raf.writeInt(age);

System.out.println("注册完毕!");
raf.close();
}
}

将每个用户信息输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Test2 {
public static void main(String[] args) throws IOException {
RandomAccessFile raf
= new RandomAccessFile("user.dat","r");
/*
* 将每个用户信息输出格式:user,pwd,nick,age
*/
for(int i=0;i<raf.length()/100;i++){
//读用户名
byte[] data = new byte[32];
raf.read(data);
String name = new String(data,"UTF-8").trim();
//读密码
raf.read(data);
String pwd = new String(data,"UTF-8").trim();
//读昵称
raf.read(data);
String nickname = new String(data,"UTF-8").trim();
//读年龄
int age = raf.readInt();
System.out.println(name+","+pwd+","+nickname+","+age);
}
}
}