NIO 파일 입출력

9380 단어 codeNIO
public class TestFile {

    //          
    @Test
    public void testWriteFile() throws Exception {
        // 1.      
        FileOutputStream fos = new FileOutputStream("basic.txt");
        // 2.          
        FileChannel fc = fos.getChannel();
        // 3.      
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 4.         ,                 。
        buffer.put("hello nio".getBytes());
        // 5.        ,     ,            。
        // 	                  。
        buffer.flip();
        //   
        fc.write(buffer);
        //    
        fos.close();
    }

    //          
    @Test
    public void testReadFile() throws Exception {
        File file = new File("basic.txt");
        // 1.      
        FileInputStream fis = new FileInputStream(file);
        // 2.   channel
        FileChannel fc = fis.getChannel();
        // 3.   buffer
        ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
        // 4.     
        fc.read(buffer);
        System.out.println(new String(buffer.array()));
    }

    //                
    @Test
    public void testCopyFile() throws Exception {
        File file = new File("basic.txt");
        // 1.          
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream("copyBasic.txt");
        // 2.       channel
        FileChannel readChannel = fis.getChannel();
        FileChannel writeChannel = fos.getChannel();
        // 3. copy  
        readChannel.transferTo(0, readChannel.size(), writeChannel);
        // writeChannel.transferFrom(readChannel, 0, readChannel.size());
        // 6.     
        fis.close();
        fos.close();

    }
}

좋은 웹페이지 즐겨찾기