我在record.txt里读取记录,读取出来的结果是第二条记录会读两次,我想要的是逐条记录读完就可以了,
  希望高人指点!谢谢!!
  record.txt
  002:03489182222:李三路:市场部助理:4:中级:02-02-2007:
  004:03489541234:于老:管理员:0:高级:14-02-2008:部分代码是这样的: while ((reinfo = io.readFromUsers("record.txt", "r")) != null) { 
reArray = reinfo.split(":"); 
num = reArray[0]; 
name = reArray[2]; 
System.out.println(num+“:”+name); 
                                                    } 
IO读取部分: 
  long indexcount = 0;
  public String readFromUsers(String fileName,String mode){ 
try{ 
RandomAccessFile readUsers =new RandomAccessFile(fileName,mode); readUsers.seek(indexcount); 
str=readUsers.readLine(); 
indexcount=readUsers.getFilePointer(); }catch (IOException e) { 
e.printStackTrace(); 
}finally{ 
try{ 
if(readUsers!=null) 
readUsers.close(); 
}catch (IOException e) { 
e.printStackTrace(); 


return str; 

解决方案 »

  1.   

    long indexcount = 0;关键是这一句 你没执行一尺io函数 indexcount就被置成了0  你应该把这个indexcount定义成类属性  
      

  2.   

    我是把long indexcount = 0 定义为类属性了,那这样可以逐条记录读取,就是最后一条记录会多读取一次啊,请问怎么解决?
      

  3.   

    我测试没有问题啊, 你试一下下面的代码:
    package dummy;import java.io.IOException;
    import java.io.RandomAccessFile;public class Dummy2 { static long indexcount = 0; /**
     * @param args
     */
    public static void main(String[] args) {
    String reinfo; while ((reinfo = readFromUsers("d:\\record.txt", "r")) != null) {
    System.out.println(reinfo);
    }
    } public static String readFromUsers(String fileName, String mode) {
    RandomAccessFile readUsers = null;
    String str = null;
    try {
    readUsers = new RandomAccessFile(fileName, mode); readUsers.seek(indexcount);
    str = readUsers.readLine();
    indexcount = readUsers.getFilePointer(); } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    if (readUsers != null)
    readUsers.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    return str;
    }}
      

  4.   

    这样分解你的函数功能是不是更加符合你的逻辑?String data=getFileData(); //将文件的内容全部一次性读到内存;//每行一个记录;
    String[] lines=data.split("\n");
    for(String reinfo: lines)
    {
    reArray = reinfo.split(":");
    num = reArray[0];
    name = reArray[2];
    System.out.println(num+“:”+name); 
    }
      

  5.   

    我也想这么提醒楼主 毕竟多次打开文件还是很消耗资源的不过要是一次全读完 就没必要用RandomAccessFile这个类了 呵呵
      

  6.   


    这个方法是按行读取的,应该不用data.split("\n")吧?