用RandomAccessFile进行I/O操作
import java.io.*;
class RandomFileTest
{
public static void main(String[] args) throws Exception
{
Student s1=new Student(1,"zhangsan",98.5);
Student s2=new Student(2,"lisi",96.5);
Student s3=new Student(3,"wangwu",76.5);
RandomAccessFile raf=new RandomAccessFile("Student.txt","rw");
s1.writeStudent(raf);
s2.writeStudent(raf);
s3.writeStudent(raf);
Student s=new Student();
raf.seek(0);
for(long i=0;i<raf.length();i=raf.getFilePointer())
{
s.readStudent(raf);
System.out.println(s.num+":"+s.name+":"+s.score);
}
raf.close();
}
}
class Student
{
int num;
String name;
double score;
Student()
{
}
Student(int num,String name,double score)
{
this.num=num;
this.name=name;
this.score=score;
}
public void writeStudent(RandomAccessFile raf) throws IOException
{
raf.writeInt(num);
raf.writeUTF(name);
raf.writeDouble(score);
}
public void readStudent(RandomAccessFile raf) throws IOException
{
raf.readInt();
raf.readUTF();
raf.readDouble();
}
}
输出的结果怎么会是
0:null:0.0
0:null:0.0
0:null:0.0
额
import java.io.*;
class RandomFileTest
{
public static void main(String[] args) throws Exception
{
Student s1=new Student(1,"zhangsan",98.5);
Student s2=new Student(2,"lisi",96.5);
Student s3=new Student(3,"wangwu",76.5);
RandomAccessFile raf=new RandomAccessFile("Student.txt","rw");
s1.writeStudent(raf);
s2.writeStudent(raf);
s3.writeStudent(raf);
Student s=new Student();
raf.seek(0);
for(long i=0;i<raf.length();i=raf.getFilePointer())
{
s.readStudent(raf);
System.out.println(s.num+":"+s.name+":"+s.score);
}
raf.close();
}
}
class Student
{
int num;
String name;
double score;
Student()
{
}
Student(int num,String name,double score)
{
this.num=num;
this.name=name;
this.score=score;
}
public void writeStudent(RandomAccessFile raf) throws IOException
{
raf.writeInt(num);
raf.writeUTF(name);
raf.writeDouble(score);
}
public void readStudent(RandomAccessFile raf) throws IOException
{
raf.readInt();
raf.readUTF();
raf.readDouble();
}
}
输出的结果怎么会是
0:null:0.0
0:null:0.0
0:null:0.0
额
解决方案 »
- 计算成绩或钱。经常遇到结果算完后为100.123456789123.。。后面好多小数如何精确到小数点后几位?
- 初学者困惑
- postgres里面有个表user,user表里有一个字段username,当username为a_b时,我要把所以带'_'的字符查出来,要怎么查呀.
- String字符串换行连接。在线等。
- 还是多线程界面死锁问题
- 这个需求怎么写啊?脑力不够。。。。。。。。。。。。。。。。55
- JDK5.0兼容以前的版本吗 兼容性怎样?
- 各位老大,how to convert Unicode code number to a character just like String.fromCharCode in jscript?
- 我用JavaHelp有两个问题,用过的兄弟进来看看好么?
- 学JAVA,请指教!
- java重写javascript的正则表达式类(原创分享)
- 用最有效的方法计算2*?=8 是什么意思
{
raf.readInt();
raf.readUTF();
raf.readDouble();
} 修改为public Student readStudent(RandomAccessFile raf) throws IOException
{
this.num = raf.readInt();
this.name = raf.readUTF();
this.score = raf.readDouble();
return this;
}
试试!
{
num = raf.readInt();
name = raf.readUTF();
score = raf.readDouble();
}
这样应该就够了吧
{
num = raf.readInt();
name = raf.readUTF();
score = raf.readDouble();
}
这样应该就够了吧