程序代码如下:
import java.io.*;
public class examFile7 {
        public static void main(String[] args) {
     String tempstr;
     String tempstr1;
     int fileline =0;
     long pointerlast = 0 ;
     try{
     RandomAccessFile inobj = new RandomAccessFile("e:\\mydir\\secondfile.txt","rw");
     while (inobj.readLine()!=null)
     fileline++;
     for(int i = 0 ; i<fileline;i++)
     {inobj.seek(i);
     tempstr=inobj.readLine();
     System.out.println(tempstr);
    
     }
     pointerlast=inobj.getFilePointer();
     System.out.println(pointerlast);
     }
    
        catch(IOException e){
        }
      
    } 
}在e:\mydir\secondfile.txt 的文件中里边的内容是
youaregoodperson
youaregoodperson
youaregoodperson
youaregoodperson
youaregoodperson
youaregoodperson
youaregoodperson
youaregoodperson程序运行的结果是
youaregoodperson
ouaregoodperson
uaregoodperson
aregoodperson
regoodperson
egoodperson
goodperson
oodperson
18
我感到疑惑的问题是:为什么System.out.println(pointerlast);打印的结果是18,我查阅了api文档资料如下
public long getFilePointer()
                    throws IOException返回此文件中的当前偏移量。 返回:
到此文件开头的偏移量(以字节为单位),在该位置发生下一个读取或写入操作我以为在文件e:\mydir\secondfile.txt中,每行是youaregoodperson只有16个字符,为什么打印结果是18呢?这是什么原因呢?请大虾帮忙解决!!谢谢。

解决方案 »

  1.   


    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */package src;/**
     *
     * @author Administrator
     */
    import java.io.*; 
    public class examFile7 { 
            public static void main(String[] args) { 
         String tempstr; 
         String tempstr1; 
         int fileline =0; 
         long pointerlast = 0 ; 
         try{ 
         RandomAccessFile inobj = new RandomAccessFile("e:\\secondfile.txt","rw"); 
         while (inobj.readLine()!=null) 
             fileline++; 
         for(int i = 0 ; i <fileline;i++) 
         {
             if(i==0)
                inobj.seek(i);
             else
                 inobj.seek(i*19);
             tempstr=inobj.readLine(); 
             System.out.println(tempstr); 
         
         } 
         pointerlast=inobj.getFilePointer(); 
         System.out.println(pointerlast); 
         } 
         
            catch(IOException e){ 
            } 
           
        }  
      

  2.   

    每行是youaregoodperson只有16个字符,为什么打印结果是18呢?
    每行结束时都有个\n换行符
    同时你的偏移量不对
      

  3.   

    每行最后有个回车换行符(0d0a),所以每行有18个byte了。