泽腾了大半天就弄出来这些。。。
读取
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();
}
}
}