java IO系统--文件I/O

一,先回顾下传统io

io其实就是为了传输数据流,这时肯定会想,数据流从哪里来,以什么格式传输.即数据存储方式和数据格式.

数据源:

1,字节数组

2,String对象

3,文件

4,管道(PipedInputStream.PipedOutputStream,PipedReader,PipedWriter)

5,Internet

不管数据在哪,读取写入数据的方法都是使用inputStream或reader的子类读取数据,使用outputStream或writer的子类写数据.我们几乎每次都要对输入进行缓冲,不管我们正在连接的是什么I/O设备,无缓冲输入是特殊情况.

下面讨论文件I/O.

1,从文件读取数据

    1)一次一个字节读取文件

    DataInputStream in = new DataInputStream(

new BufferedInputStream(

new FileInputStream(filename)));//装饰者模式

   while(in.available()!=0){

   System.out.print((char)in.readByte());   

   }

    2)字符读取

BufferedReader in = new BufferedReader(new FileReader(filename));//缓冲是为了提高速度

2,往文件写入数据

1)基于字节写入,FileOutputStream

DataOutputStream out = new DataOutputStream(

new BufferedOutputStream(

new FileOutputStream(filename)));


2)基于字符写入,FileWriter
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(filename)));
快捷方式:PrintWriter out = new PrintWriter(filename);

TextFIle类简化了对文件的读写

二,NIO

NIO使用了通道和缓冲器

1,文件读写:

FileChannel in = new FileInputStream(filename1).getChannel();//这个文件的数据将会输入到buffer里

FileChannel out = new FIleOutputStream(filename2).getChannel();//从buffer里读取数据写入到这个文件里

ByteBuffer buffer = ByteBuffer.allocate(BSIZE);//创建BSIZE大小的缓冲器

//根据需要加入基本类型视图缓冲器,例如IntBuffer ib = buffer.asIntBuffer();

//ByteBuffer是将数据移进移出通道的唯一方式,不能将基本类型的缓冲器转换成ByteBuffer,而是经由视图缓冲器将基本类型数据移进移出ByteBuffer.

while(in.read(buffer)!=-1){//没到文件末尾

buffer.flip();//为写入做准备

out.writer(buffer);

buffer.clear();//为读取做准备

}


或者两个通道也可以直接相连

FileChannel in = new FileInputStream(filename1).getChannel();

FileChannel out = new FIleOutputStream(filename2).getChannel();

in.transferTo(0,in.size(),out);//or out.transferFrom(in,0,in.size());

2,文件加锁
只能获得通道上的锁,不能获得缓冲器的锁,而且SocketChannel,DatagramChannel,ServerSocketChannel不需要加锁,因为它们是从单进程实体继承而来,我们通常不在两个进程之间共享网络socket.
FileOutputStream fos = new FileOutputStream(filename);
FileLock fl = fos.getChannel().tryLock();//或者lock()阻塞式的,tryLock()是非阻塞式的.这个无参方法是 对整个文件加锁
当文件极大的时候,需要对文件 部分加锁,方法是
tryLock(long position,long size,boolean shared)    //position和size决定加锁区域,shared:是否共享锁
或者
lock(long position,long size,boolean shared)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值