java2019. 9. 22. 15:21

ex)


public class NioSample {
	
	
	public NioSample() {
		super();
		
		basicWriteAndRead();
		
	}
	
	
	private void basicWriteAndRead() {
		String fullPath = "C:"+File.separator+"Users"+File.separator+"Lee"+File.separator+"test"+File.separator+"nio.txt";
		
		try {
			writeFile(fullPath, "Nio sample");
			readFile(fullPath);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			
		}
		
		
	}




	private void writeFile(String fullPath, String data) throws Exception {
		FileChannel channel = new FileOutputStream(fullPath).getChannel();//channel 객체 생성
		byte [] byteData = data.getBytes();
		ByteBuffer buffer = ByteBuffer.wrap(byteData); //ByteBuffer 생성방법 : bytearray를 wrap method에 전달
		channel.write(buffer); // write 함수 호출
		channel.close();		
	}
	
	private void readFile(String fullPath) throws Exception{
		FileChannel channel = new FileInputStream(fullPath).getChannel();//channel 객체 생성
		ByteBuffer buffer = ByteBuffer.allocate(1024);// ByteBuffer 할당
		channel.read(buffer);//read 메소드에 버퍼를 전달
		
		buffer.flip(); //buffer 객체의 맨 앞으로 이동
		//Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. 
		while(buffer.hasRemaining()) {
			System.out.print((char)buffer.get());// 한 바이트씩 읽음.
		}
		channel.close();
	}
	
	

}

 

출처 : 자바의 신

Posted by easy16