欢迎来到天天文库
浏览记录
ID:42606113
大小:4.54 MB
页数:8页
时间:2019-09-18
《Java SE 095 Java字符流详解 续_免费下载》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、JavaSE095Java字符流详解续一、FileWriterFileWriter创建一个可以写文件的Writer类。FileWriter继承于OutputStreamWriter。它最常用的构造方法如下:FileWriter(StringfilePath);FileWriter(StringfilePath,booleanappend);FileWriter(FilefileObj)append:如果为true,则将字节写入文本末尾处,而不是写入文件开始处。packagecom.javase.io2;importjava.io.FileWriter;
2、publicclassFileWriter1{publicstaticvoidmain(String[]args)throwsException{Stringstr="helloworldwelcomenihao";//FileWriter操纵的是字符或者是字符数组,字符串与字符数组是两个不同的对象,可以将其转换成字符数组char[]buffer=newchar[str.length()];//将字符串儿里面的内容复制到buffer数组str.getChars(0,str.length(),buffer,0);FileWriterwriter=newF
3、ileWriter("file2.txt");for(inti=0;i4、length()];tmp.getChars(0,tmp.length(),ch,0);CharArrayReadercar=newCharArrayReader(ch);inti;while(-1!=(i=car.read())){System.out.println((char)i);}}}这个类既能读,又能写!packagecom.javase.io2;importjava.io.IOException;importjava.io.RandomAccessFile;publicclassRandomAccessFile1{publicstatic5、voidmain(String[]args)throwsIOException{Personp=newPerson(1,"JieLin",160);RandomAccessFileraf=newRandomAccessFile("test.txt","rw");p.write(raf);Personp1=newPerson();raf.seek(0);//让读的位置重新回到文件开头p1.read(raf);System.out.println(p1.id+""+p1.name+""+p1.height);}}classPerson{intid;Stri6、ngname;doubleheight;publicPerson(){}publicPerson(intid,Stringname,doubleheight){this.id=id;this.name=name;this.height=height;}publicvoidwrite(RandomAccessFileraf)throwsIOException{raf.writeInt(id);raf.writeUTF(name);raf.writeDouble(height);}publicvoidread(RandomAccessFileraf)thr7、owsIOException{this.id=raf.readInt();this.name=raf.readUTF();this.height=raf.readDouble();}}
4、length()];tmp.getChars(0,tmp.length(),ch,0);CharArrayReadercar=newCharArrayReader(ch);inti;while(-1!=(i=car.read())){System.out.println((char)i);}}}这个类既能读,又能写!packagecom.javase.io2;importjava.io.IOException;importjava.io.RandomAccessFile;publicclassRandomAccessFile1{publicstatic
5、voidmain(String[]args)throwsIOException{Personp=newPerson(1,"JieLin",160);RandomAccessFileraf=newRandomAccessFile("test.txt","rw");p.write(raf);Personp1=newPerson();raf.seek(0);//让读的位置重新回到文件开头p1.read(raf);System.out.println(p1.id+""+p1.name+""+p1.height);}}classPerson{intid;Stri
6、ngname;doubleheight;publicPerson(){}publicPerson(intid,Stringname,doubleheight){this.id=id;this.name=name;this.height=height;}publicvoidwrite(RandomAccessFileraf)throwsIOException{raf.writeInt(id);raf.writeUTF(name);raf.writeDouble(height);}publicvoidread(RandomAccessFileraf)thr
7、owsIOException{this.id=raf.readInt();this.name=raf.readUTF();this.height=raf.readDouble();}}
此文档下载收益归作者所有