java基础java中对文件的读写操作之比较

java基础java中对文件的读写操作之比较

ID:34723787

大小:64.46 KB

页数:3页

时间:2019-03-10

java基础java中对文件的读写操作之比较_第1页
java基础java中对文件的读写操作之比较_第2页
java基础java中对文件的读写操作之比较_第3页
资源描述:

《java基础java中对文件的读写操作之比较》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库

1、http://www.lampbrother.netJava中对文件的读写操作之比较Java对文件进行读写操作的例子很多,让初学者感到十分困惑,我觉得有必要将各种方法进行一次分析,归类,理清不同方法之间的异同点。一.在JDK1.0中,通常是用InputStream&OutputStream这两个基类来进行读写操作的。InputStream中的FileInputStream类似一个文件句柄,通过它来对文件进行操作,类似的,在OutputStream中我们有FileOutputStream这个对象。用FileInputStream来读取数据的常用方法是:File

2、InputStreamfstream=newFileInputStream(args[0]);DataInputStreamin=newDataInputStream(fstream);用in.readLine()来得到数据,然后用in.close()关闭输入流。完整代码见Example1。用FileOutputStream来写入数据的常用方法是:FileOutputStreamoutout=newFileOutputStream("myfile.txt");PrintStreamp=newPrintStream(out);用p.println()来写入数据

3、,然后用p.close()关闭输入。完整代码见Example2。二.在JDK1.1中,支持两个新的对象Reader&Writer,它们只能用来对文本文件进行操作,而JDK1.1中的InputStream&OutputStream可以对文本文件或二进制文件进行操作。http://www.lampbrother.net用FileReader来读取文件的常用方法是:FileReaderfr=newFileReader("mydata.txt");BufferedReaderbr=newBufferedReader(fr);用br.readLing()来读出数据,然

4、后用br.close()关闭缓存,用fr.close()关闭文件。完整代码见Example3。用FileWriter来写入文件的常用方法是:FileWriterfw=newFileWriter("mydata.txt");PrintWriterout=newPrintWriter(fw);在用out.print或out.println来往文件中写入数据,out.print和out.println的唯一区别是后者写入数据或会自动开一新行。写完后要记得用out.close()关闭输出,用fw.close()关闭文件。完整代码见Example4。---------

5、-----------------------------------------------------followingisthesourcecodeofexamples------------------------------------------------------Example1://FileInputDemo//DemonstratesFileInputStreamandDataInputStreamimportjava.io.*;classFileInputDemo{publicstaticvoidmain(Stringargs[]){

6、//args.lengthisequivalenttoargcinCif(args.length==1){try{http://www.lampbrother.net//OpenthefilethatisthefirstcommandlineparameterFileInputStreamfstream=newFileInputStream(args[0]);//ConvertourinputstreamtoaDataInputStreamDataInputStreamin=newDataInputStream(fstream);//Continuetore

7、adlineswhiletherearestillsomelefttoreadwhile(in.available()!=0){//PrintfilelinetoscreenSystem.out.println(in.readLine());}in.close();}catch(Exceptione){System.err.println("Fileinputerror");}}elseSystem.out.println("Invalidparameters");}}Example2://FileOutputDemo//DemonstrationofFil

8、eOutputStreamandPrintStrea

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。