java NIO读写文件

/**
	 * 从文件中读取数据
	 */
	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设置为0
			buffer.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();
	}  
      
      
  }

你可能感兴趣的:(java NIO读写文件)