java NIO read file
try{ String matrixFilePath=LotteryNumberUtils.getMatrixPath("S6",reds.size(),cse); if (logger.isDebugEnabled())logger.debug("----"+matrixFilePath+"----"); File matrixFile=new File(matrixFilePath); if(!matrixFile.exists())return this.message("***"); fis=new FileInputStream(matrixFile); fc=fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); CharBuffer charBuffer = CharBuffer.allocate(1024); Charset charset = Charset.forName("UTF-8"); CharsetDecoder decoder = charset.newDecoder(); while (fc.read(buffer) != -1) { buffer.flip();//写出前操作 //while (buffer.hasRemaining()) {//枚举byteBuffer中的数据 decoder.decode(buffer, charBuffer, false); charBuffer.flip(); if (logger.isDebugEnabled())logger.debug("----"+charBuffer+"----"); //} buffer.clear();//读入前操作 charBuffer.clear(); } } catch (FileNotFoundException ffe){ if (logger.isDebugEnabled())logger.debug("----"+ffe.getMessage()+"matrix file not found"); return this.message("***"); } catch (IOException e) { if (logger.isDebugEnabled())logger.debug("----file read error matrix----"); e.printStackTrace(); } finally { try { if(fc!=null)fc.close(); if(fis!=null)fis.close(); } catch (IOException e) { if (logger.isDebugEnabled())logger.debug("----stream close error----"); e.printStackTrace(); } }
参考:
http://java.sun.com/developer/technicalArticles/releases/nio/#Resources
http://www.blogjava.net/cherishchen/archive/2010/07/13/326000.html
http://www.cnblogs.com/focusj/archive/2011/11/03/2231583.html