public class NIODemo { //TODO 文件锁定时数据需提前备份 public static void main(String[] args) throws Exception { File file = new File("F:"+ File.separator+"vm_realpath"+File.separator+"vm.log"); FileOutputStream outputStream = new FileOutputStream(file); FileChannel channel = outputStream.getChannel();//获取文件输入的Channel FileLock fileLock = channel.tryLock();//尝试获取文件锁 if(fileLock != null){//已经获取了文件锁 System.out.println("已经获取了文件锁,当前文件被锁定"); TimeUnit.SECONDS.sleep(10);//锁10秒 fileLock.release();//解锁 } channel.close(); outputStream.close(); } }
字符集
public class NIODemo { public static void main(String[] args) throws Exception { SortedMap<String,Charset> map = Charset.availableCharsets() ; for(Map.Entry<String,Charset> entry:map.entrySet()){ //查看支持的编码 System.out.println(entry.getKey() + "-"+entry.getValue()); } } }
编码与解码
public class NIODemo { public static void main(String[] args) throws Exception { Charset charset = Charset.forName("UTF-8") ;//创建一个“UTF-s"的编码器 CharsetEncoder encoder= charset.newEncoder() ; //获取编码器 CharsetDecoder decoder= charset.newDecoder() ; //获取解码器 CharBuffer buffer = CharBuffer.allocate(20);//分配空间数据 buffer.put("万邦皆下品,惟有读书高"); buffer.flip();//重置缓冲区 ByteBuffer encodeBuffer = encoder.encode(buffer) ;//对缓冲区中的数据进行编码 System.out.println(decoder.decode(encodeBuffer)); } }