FileChannel操作

本文介绍如何使用Java进行文件的读写操作,并利用FileChannel实现文件锁,确保文件操作的同步安全性。

泽腾了大半天就弄出来这些。。。

读取

                        RandomAccessFile in =null;
				FileLock lock = null;
				try {
					in = new RandomAccessFile(new File(url.getFile()),"rw");//FileInputStream不能lock
					FileChannel channel = in.getChannel();
					ByteBuffer buffer = ByteBuffer.allocate(1024);
					Charset charset = Charset.forName("UTF-8");
					CharsetDecoder decoder = charset.newDecoder();
					//文件读入buffer
					lock = channel.tryLock();
					while(channel.read(buffer)!= -1) {
						buffer.flip();//将limit设为position并将position设为0
						context.append(decoder.decode(buffer));
						buffer.compact();
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					if(null !=in) {
						in.close();
					}
					if(null != lock) {
						//判断是否锁还存在,如果流已经关闭,则会自动不存在
						if(lock.isValid()) {
							lock.release();
						}
					}
				}



写入
            FileChannel channel = null;
			FileOutputStream outp = null;
			FileLock lock = null;
			try {
				//保存文件需要同步
				URL url = Thread.currentThread().getContextClassLoader().getResource("notice/file/"+fileName);
				//out = new RandomAccessFile(new File(url.getFile()),"rw");不会完全覆盖文件。。
				outp = new FileOutputStream(new File(url.getFile()));
				channel = outp.getChannel();
				ByteBuffer buffer = ByteBuffer.wrap(content.getBytes());
				
				lock = channel.tryLock();
				while(buffer.hasRemaining()) {
					channel.write(buffer);
				}
				buffer.clear();
				channel.force(true);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if(null != outp) {
					outp.close();
					channel.close();
				}
				if(null != lock) {
					if(lock.isValid()) {
						lock.release();
					}
				}
			}



转载于:https://my.oschina.net/u/782865/blog/220363

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值