RandomAccessFile的简单使用

来源:互联网 发布:lol职业选手训练软件 编辑:程序博客网 时间:2024/04/30 02:38

RandomAccessFile的简单使用


public class ReplaceString {    public static void main(String[] args) throws IOException {                File file=new File("stuent.txt");        //生产RandomAccessFile类,对文件file有读写功能        RandomAccessFile raf=new RandomAccessFile(file,"rw");        String line=null;        //下次写文件时,字符串放入的位置        int num1=0;        while((line=raf.readLine())!=null){            String string=null;            raf.seek(num1);            //如果字符串有包含"name"时            if(line.contains("name")){                //替换"name"为"MingZi",并赋值给string                string=line.replace("name","MingZi");                //把字符串的字节数组写入到文件中                raf.write(string.getBytes());                //获取下次写入的位置                num1+=string.getBytes().length;            }            //字符串中不包含"name"时,直接写入该字符串,并获取下次写入的位置             else{                raf.write(line.getBytes());                num1+=line.getBytes().length;            }        }        raf.close();    }}
/** * 随机生产20个学生,并写入stuent.txt文件中 */public class OutPutFile {    private List<Student> list;    public static void main(String[] args) throws IOException {        Student s=new Student();        String string=new String();        OutPutFile outPutFile=new OutPutFile();        outPutFile.list=outPutFile.toListStudent();        FileOutputStream outPutFile1=new FileOutputStream("stuent.txt");        OutputStreamWriter outputStreamWriter=new OutputStreamWriter(outPutFile1);        Iterator<Student> iterator=outPutFile.list.iterator();        while(iterator.hasNext()){            s=iterator.next();            string="name:"+s.getName()+" "+"age:"+s.getAge()+" address"+s.getAddress();            outputStreamWriter.write(string+"\r\n");        }        outputStreamWriter.close();    }    public List<Student> toListStudent(){        List<Student> list=new ArrayList<>();        Student student;        for(int i=0;i<10;i++)        {            student=new Student();            student.setName("studnet"+i);            student.setAge(20+i);            student.setAddress(i+"");            list.add(student);        }        return list;    }

return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; }}



1 0
原创粉丝点击