java.nio.* 篇(1) FileChannel AsynchronousFileChannel ServerSocket Socket 使用案例

博客提供了Java相关技术的使用示例,包括java.nio.FileChannel、java.nio.AsynchronousFileChannel的使用demo,以及java.net.ServerSocket和java.net.Socket的使用demo,还给出了BIO的参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java.nio.FileChannel 使用demo

 /**
     * @description: demos of jdk8 java.nio.FileChannel class
     * java.nio.FileChannel 作用:FileChannel 是文件通道类, 管道形式打开文件
     * FileChannel MappedByteBuffer 例子:
     */
    @Test
    public void testFileChannel() throws IOException {

        //filechannel 写入demo
        byte[] bytes =  "hello world".getBytes();
        RandomAccessFile fis = new RandomAccessFile("D:\\soft\\doc\\file_channel.txt","rw");
        FileChannel fileChannel = fis.getChannel();
        MappedByteBuffer writembb = fileChannel.map(FileChannel.MapMode.READ_WRITE,0,1024*1024);
        writembb.put(bytes,0,bytes.length);
        fis.close();
        fileChannel.close();

        //filechannel 读取demo
        byte[] rbytes = new byte[1024];
        fis = new RandomAccessFile("D:\\soft\\doc\\file_channel.txt","rw");
        fileChannel = fis.getChannel();
        MappedByteBuffer readmbb = fileChannel.map(FileChannel.MapMode.READ_WRITE,0,1024*1024);
        readmbb.position(0);
        readmbb.get(rbytes,0,bytes.length);
        String rb = new String(rbytes);
        System.out.println(rb);

     }

java.nio.AsynchronousFileChannel 使用demo

 

/**
     * @description: demos of jdk8 java.nio.AsynchronousFileChannel class
     * java.nio.AsynchronousFileChannel 作用:AsynchronousFileChannel 是 异步文件通道类, 管道形式打开文件
     * FileChannel MappedByteBuffer 例子:
     */
    @Test
    public void testAsynchronousFileChannel() throws IOException {

        //asynchronousFileChannel 写入demo
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put("hello".getBytes());
        AsynchronousFileChannel wfileChannel = AsynchronousFileChannel.open(Paths.get("D:/soft/doc/file_channel2.txt"), StandardOpenOption.CREATE,StandardOpenOption.WRITE);
        byteBuffer.flip();
        wfileChannel.write(byteBuffer, 0, null, new CompletionHandler<Integer, Object>() {
            @Override
            public void completed(Integer result, Object attachment) {
                try {
                    wfileChannel.force(true);
                    wfileChannel.close();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void failed(Throwable exc, Object attachment) {

            }
        });


        //asynchronousFileChannel 读取demo
        byteBuffer.clear();
        AsynchronousFileChannel rFileChannel = AsynchronousFileChannel.open(Paths.get("D:/soft/doc/file_channel2.txt"), StandardOpenOption.READ);
        rFileChannel.read(byteBuffer, 0, null, new CompletionHandler<Integer, Object>() {
            @Override
            public void completed(Integer result, Object attachment) {

                try {
                    byteBuffer.flip();
                    System.out.println(new String(byteBuffer.array()));
                    rFileChannel.close();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void failed(Throwable exc, Object attachment) {

            }
        });


    }

 

java.net.ServerSocket 使用demo

 /**
     * @description: demos of jdk8 java.net.ServerSocket class
     * 创建服务端,有客户端连接后发送hello 字符串,并接受客户端reply 回复
     *
     * */
    @Test
    public void testServer() throws IOException {

        ServerSocket serverSocket = new ServerSocket(8679);
        while(true){
            Socket socket = serverSocket.accept();
            socket.getOutputStream().write("hello".getBytes());
            try{
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                byte[] bytes = new byte[1024];
                int read = 0;
                while ((read =socket.getInputStream().read(bytes))>0){
                    byteBuffer.put(bytes,0,read);
                    byteBuffer.flip();
                    String rs = new String(byteBuffer.array());
                    System.out.println(rs);
                    byteBuffer.clear();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(!socket.isClosed()) {
                    try {
                        socket.close();
                    }catch (Exception e1){
                        e1.printStackTrace();
                    }

                }
            }

        }
    }

java.net.Socket 使用demo

 /**
     * @description: demos of jdk8 java.net.Socket class
     * 创建客户端,连接到服务端后接收到hello 字符串,并接向服务端发送reply 字符串回复
     */
    @Test
    public void testClient() throws IOException {

        Socket socket = new Socket("127.0.0.1", 8679);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byte[] bytes = new byte[1024];
        int read = 0;
        while ((read = socket.getInputStream().read(bytes)) > 0) {

            byteBuffer.put(bytes, 0, read);
            byteBuffer.flip();
            String rs = new String(byteBuffer.array());
            byteBuffer.clear();
            System.out.println(rs);
            socket.getOutputStream().write("reply".getBytes());
        }
    }

 

BIO 参考《通俗易懂的JAVA BIO NIO AIO 原理白话文解释,区别,优缺点及代码使用案例》

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

峡谷电光马仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值