File file = new File(filePath);
BufferedOutputStream stream = null;
FileOutputStream fstream = null;
FileChannel fileChannel = null;
FileLock fileLock = null;
try {
fstream = new FileOutputStream(file);
fileChannel = fstream.getChannel();
fileLock = fileChannel.tryLock();
if (null != fileLock && fileLock.isValid()) {
stream = new BufferedOutputStream(fstream);
stream.write(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != fileLock) {
fileLock.release();
}
// if (null != fileChannel) {
// fileChannel.close();
// }
if (stream != null) {
stream.close();
}
if (null != fstream) {
fstream.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
在关闭
FileChannel 会导致文件流被关闭,特别是写较小文件时候,这个说明JDK8中,这个不需要去手动关闭