日期:2014-05-20  浏览次数:20760 次

亲们,给解决一下下边这个问题吧先谢了。
将三行内容写进一个文件然后再读出,为什么在读第一行的时候first读不出来呢,还有当加上循环的时候第一次循环的第一行的first不能读出而从第二次开始便就能读出了是怎么回事。希望劳烦大家给看看。
import java.io.*;
public class shiyan6_2
{
public static void main(String[] args)
{
String str[]={"First line\n","Second line\n","Last line\n"};
try{
RandomAccessFile rf=new RandomAccessFile("shiyan6_2.txt","rw");
System.out.println("\n文件指针位置:"+rf.getFilePointer());
System.out.println("文件长度为:"+rf.length());
rf.seek(rf.length());
System.out.println("文件指针现在的位置为:"+rf.getFilePointer());
for(int i=0;i<3;i++)
rf.writeChars(str[i]);
rf.seek(10);
System.out.println("\n选择显示的文件内容:");
String s;
s=rf.readLine();//问题出在这,如果换成循环
                                                  while((s=rf.readLine())!=null);
                                          时只有第一次的first不会被读入。
                                                   你们copy一份运行运行看看,麻烦大家了。

                        System.out.println(s);
rf.close();
}
catch(FileNotFoundException fone){}
catch(IOException ioe){}
}
}
------解决方案--------------------
3点建议:
1 rf.seek(0);     //从0开始。
2 s=rf.readLine();//后面加上一句输出。
  System.out.println(s);
3 建议把writeChars() 改成writeBytes().

其中第一点最重要了。
public class Shiyan6_2		//类名第一个字母大写。
{
public static void main(String[] args)
{
String str[]={"First line\n","Second line\n","Last line\n"};
try
{
RandomAccessFile rf=new RandomAccessFile("shiyan6_2.txt","rw");
System.out.println("\n文件指针位置:"+rf.getFilePointer());
System.out.println("文件长度为:"+rf.length());
rf.seek(rf.length());
System.out.println("文件指针现在的位置为:"+rf.getFilePointer());
for(int i=0;i<3;i++)
rf.writeChars(str[i]); //最好用writeBytes()
rf.seek(0); //从0开始,为什么要是 10呢?
System.out.println("\n选择显示的文件内容:");
String s;
s=rf.readLine();//问题出在这,如果换成循环,这行不要的话,下面这句也不要。
System.out.println(s);//输出字符串,正好是第一行。
while((s=rf.readLine())!=null)
{
                           System.out.println(s);
}
rf.close();
}
catch(FileNotFoundException fone)
{
fone.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}