接二楼,解决的办法就是凑一个固定大小的字符串可以定义一个方法来判断用户输入的姓名是多大的,然后将其调整到固定大小,然后再存到文件用,如果考虑俄国人的话,咱就弄个15个字符的固定大小吧,代码如下:- import java.io.*;
- public class RandomAccessFileDemo {
- public static void main(String[] args) throws IOException {
- //writeFile();
- readFile();
- }
- public static void writeFile() throws IOException {
- RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");
- //获得控制台输入流
- BufferedReader bfbr = new BufferedReader(new InputStreamReader(System.in));
- System.out.println("请输入用户名和年龄,以逗号隔开,结束请输入over");
-
- String line = null;
- //可以无限输入
- while((line = bfbr.readLine()) != null){
- //结束标记
- if("over".equals(line.toLowerCase()))
- break;
- String[] strs = line.split(",");
- raf.write(changeSize(strs[0]).getBytes());//写入changeSize函数返回的调好大小的姓名
- raf.writeInt(Integer.parseInt(strs[1].trim()));//用trim函数清除空格
- }
-
- bfbr.close();
- raf.close();
-
- }
- private static String changeSize(String string) {
- byte[] buf = string.getBytes();
- //System.out.println(buf.length);
- StringBuilder sb = new StringBuilder(string);
-
- int x = (30 - buf.length)/2;//计算需要添加空格的次数
-
- //添加空格一个空格对应一个字节
- for(int i=0; i<x; i++){
- sb.append(" ");
- }
-
- String str = sb.toString();
- //System.out.println(str.getBytes().length);
- return str;
- }
- public static void readFile() throws IOException {
- RandomAccessFile raf = new RandomAccessFile("raf.txt", "r");
- // raf.skipBytes(8*2);
- byte[] buf = new byte[30];
- int len = 0;
- while((len = raf.read(buf)) != -1){
- String name = new String(buf, 0, len);
- int age = raf.readInt();
- System.out.println("姓名:" + name);
- System.out.println("年龄:" + age);
- }
-
-
- raf.close();
- }
- }
复制代码 希望对楼主有帮助 |