java NIO读写文件

来源:互联网 发布:淘宝推广包括腾讯新闻 编辑:程序博客网 时间:2024/05/16 06:42
/** * 从文件中读取数据 */public static void readDataFormFile(String path) {try (FileInputStream fis = new FileInputStream(path);) {// 1获取通道FileChannel fc = fis.getChannel();// 2创建缓冲区ByteBuffer buffer = ByteBuffer.allocate(1024);// 3从Channel读取到Buffer中fc.read(buffer);// 4把limit设置为当前的position值 ;把position设置为0buffer.flip();// 5循环判断缓冲区是否有元素存在while (buffer.hasRemaining()) {byte b = buffer.get();System.out.println((char) b);}} catch (Exception e) {e.printStackTrace();}}/** * 写数据 * @param path 文件路径 */  public static void writeDataToFile(String path){ byte message[] = { 83, 111, 109, 101, 32,          98, 121, 116, 101, 115, 46 };  try( FileOutputStream fout = new FileOutputStream(path);) { FileChannel fc = fout.getChannel();                ByteBuffer buffer = ByteBuffer.allocate( 1024 );                for (int i=0; i<message.length; ++i) {            buffer.put( message[i] );        }                buffer.flip();        fc.write( buffer );       System.out.println("写入数据成功!");} catch (Exception e) {e.printStackTrace();}                }

0 0