NIO学习demo

package io_test; 


import java.io.File; 
import java.io.FileInputStream; 
import java.nio.ByteBuffer; 
import java.nio.channels.FileChannel; 


public class TestNIO { 


    public static void main(String[] args) { 
        // File.separator==D:\\test\\hello.txt 
        String fileName = "D:" + File.separator + "test" + File.separator + "hello.txt"; 
        testNIO(fileName); 


    } 

    private static void testNIO(String fileName) { 
        FileInputStream fin; 
        try { 
            fin = new FileInputStream(fileName); 
            // 获取通道 
            FileChannel fc = fin.getChannel(); 
            // 创建一个缓冲区 
            ByteBuffer buffer = ByteBuffer.allocate(1024); 
            // 将数据从通道读到缓冲区中 
            fc.read(buffer); 
            // 将数据从缓冲区中拿出来 
            String input = new String(buffer.array()).trim(); 
            System.out.println(input); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}

猜你喜欢

转载自blog.51cto.com/10983206/2564131