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(); } }
출처 : 자바의 신
'java' 카테고리의 다른 글
Simple server & client socket 예제 (0) | 2019.09.22 |
---|---|
Buffer class의 이해 (0) | 2019.09.22 |
Serializable interface, transient 예약어, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream 예제 (0) | 2019.09.22 |
FileReader 및 BufferedReader + (Scanner) (0) | 2019.09.22 |
FileWriter 및 BufferedWriter 텍스트기반 처리 (0) | 2019.09.22 |