java的读和写

1、流: 它是通过缓冲机制将数据从生产者(如键盘、磁盘文件、内存或其他设备)传送到接受该数据的消费者(如屏幕、文件或者内存等)的这一过程的抽象。 2、有关的java包: java.io包中包括许多类提供许多有关文件的各个方面操作。 3、有关文件名及目录名的类:file 类独立于系统平台,利用构造函数 file( string path)、 file(string path, string filename)、 file(file dir, string name) 等创建出file 对象;再利用canread() 、canwrite()、 getparent()、 getpath()等成员函数实现对文件的各个属性的操作。 import java.io.*; public class filetest { public static void main(string []args) { string filename=c:/temp/myfile.dat file myfile=new file(filename); if( ! myfile. exists() ) { system.err.println(cant find filename); return; } system.out.println(file filename is myfile.length() bytes long !); if( myfile. isdirectory() ) { system.err.println(file filename is a directory !); return; } } } 4、有关文件内容(数据)操作的类: 4.1 输入输出抽象基类inputstream/outputstream ,实现文件内容操作的基本功能函数read()、 write()、close()、skip()等;一般都是创建出其派生类对象(完成指定的特殊功能)来实现文件读写。在文件读写的编程过程中主要应该注意异常处理的技术。 4.2 fileinputstream/fileoutputstream: 用于本地文件读写(二进制格式读写并且是顺序读写,读和写要分别创建出不同的文件流对象); 本地文件读写编程的基本过程为: ① 生成文件流对象(对文件读操作时应该为fileinputstream类,而文件写应该为fileoutputstream类); ② 调用fileinputstream或fileoutputstream类中的功能函数如read()、write(int b)等)读写文件内容; ③ 关闭文件(close())。 4.3 pipedinputstream/pipedoutputstream: 用于管道输入输出(将一个程序或一个线程的输出结果直接连接到另一个程序或一个线程的输入端口,实现两者数据直接传送。操作时需要连结); 4.3.1 管道的连接: 方法之一是通过构造函数直接将某一个程序的输出作为另一个程序的输入,在定义对象时指明目标管道对象 pipedinputstream pinput=new pipedinputstream(); pipedoutputstream poutput= new pipedoutputstream(pinput); 方法之二是利用双方类中的任一个成员函数 connect()相连接 pipedinputstream pinput=new pipedinputstream(); pipedoutputstream poutput= new pipedoutputstream(); pinput.connect(poutput); 4.3.2 管道的输入与输出: 输出管道对象调用write()成员函数输出数据(即向管道的输入端发送数据);而输入管道对象调用read()成员函数可以读起数据(即从输出管道中获得数据)。这主要是借助系统所提供的缓冲机制来实现的。 4.4、随机文件读写: randomaccessfile类(它直接继承于object类而非inputstream/outputstream类),从而可以实现读写文件中任何位置中的数据(只需要改变文件的读写位置的指针)。 随机文件读写编程的基本过程为: ① 生成流对象并且指明读写类型; ② 移动读写位置; ③ 读写文件内容; ④ 关闭文件。 stringbuffer buf=new stringbuffer(); char ch; while( (ch=(char)system.in.read()) !=n) { buf.append( ch); } //读写方式可以为r or rw randomaccessfile myfilestream=new randomaccessfile(myfile.dat, rw); myfilestream . seek(myfilestream.length()) ; myfilestream.writebytes(buf.tostring()); //将用户从键盘输入的内容添加到文件的尾部 myfilestream.close(); 4.5 datainput/dataoutput接口:实现与机器无关的各种数据格式读写(如readchar() 、readint()、readlong()、readfloat(),而readline()将返回一个string)。其中randomaccessfile类实现了该接口,具有比fileinputstream或fileoutputstream类更灵活的数据读写方式。 4.6 标准输入输出流:system.in(如:char c=system.in.read())和system.out(如:system.out.println()、system.out.println())。 try { char ch=system.in.read(); //返回二进制数据(低8位为键盘的ascii码) } catch(ioexception e) { } 4.7、文件操作的一般方法: (1)生成一个输入输出文件类的对象(根据所要操作的类型); (2)调用此类的成员函数实现文件数据内容的读写;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值