JAVA BIO,JAVA NOI案列

JAVA BIO,JAVA NOI案列

一、Java BIO 案列

1、BIO 读取文件
import java.io.File;
import java.io.FileInputStream;
public class ReadFileBIO {

    public static void main(String[] args) {

        //文件对象
        File file = new File("BIO.txt");

        //文件输出流
        FileInputStream fileInputStream = null;

        try {

            //文件输出流实例化
            fileInputStream = new FileInputStream(file);

            //创建byte数组
            byte[] bytes = new byte[1024];

            //将流读到byte数组
            while (fileInputStream.read(bytes) != -1) {

                //byte数组转String打印,去除前后空格
                System.out.printf(new String(bytes).trim());

            }

        } catch (Exception e) {

            //异常处理
            e.printStackTrace();

        } finally {

            //关闭输入流
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        
    }
    
}
2、BIO 写文件
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

public class WriteFileBIO {

    public static void main(String[] args) {
        //写入文本
        String txt = "同步并阻塞(传统阻塞型),服务器实现模式为一个连接对应一个线程。及客户端有连接请求时,服务器就启动一个线程进行处理,当这个连接不做任何操作时(读写),线程会一直等待客户端的读写请求,等待(阻塞)的这段时间对线程资源造成很大的开销,浪费线程资源";

        //写入的文件
        File file = new File("BIO.txt");

        //文件输出流
        FileOutputStream fileOutputStream = null;

        try {
            //文件输出流实例化(创建新的)
            fileOutputStream = new FileOutputStream(file);

            //文件输出流实例化(追加)
            //fileOutputStream = new FileOutputStream(file,true);

            //文本转数组
            byte[] bytes = txt.getBytes(StandardCharsets.UTF_8);

            //写
            fileOutputStream.write(bytes);

        } catch (Exception e) {

            //异常处理
            e.printStackTrace();

        } finally {

            //输出流关闭
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        
    }

}
3、BIO文件拷贝

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ReadWriteFileBIO {

    public static void main(String[] args) {

        //源文件
        File inputFile = new File("BIO.txt");

        //目标文件
        File outputFile = new File("BIO2.txt");

        //文件输入流
        FileInputStream fileInputStream = null;

        //文件输出流
        FileOutputStream fileOutputStream = null;


        try {

            //文件输入流实例化
            fileInputStream = new FileInputStream(inputFile);

            //文件输出流实例化
            fileOutputStream = new FileOutputStream(outputFile);


            //创建byte数组
            byte[] bytes = new byte[1024];

            //循环读取输入流的数据到byte数组,然后将byte数组的数据写到输出流
            while (true){
                //读取输入流的数据到byte数组
                int read = fileInputStream.read(bytes);

                //判断输入流数据是否读取完毕,读取完毕退出循环
                if (read == -1){
                    break;
                }

                //将byte数组的数据写到输出流
                fileOutputStream.write(bytes);
            }

        } catch (Exception e) {

            //异常处理
            e.printStackTrace();

        } finally {

            //流关闭
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
4、BIO 网络编程案列
(1)BIO 服务端


import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {

    public static void main(String[] args) {

        //创建Socket服务
        ServerSocket serverSocket = null;

        try {
            //创建线程池
            ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

            //实例化Socket服务并绑定端口
            serverSocket = new ServerSocket(6666);

            System.out.println("服务器启动了...");

            //无限循环,等到客户端连接
            while (true) {

                System.out.println("等待客户端连接...");

                /**
                 * serverSocket.accept()有阻塞的功能,没有客户端连接到服务器,就不会进入下一步
                 */
                Socket socket = serverSocket.accept();

                System.out.println("连接到一个客户端...");

                //每一个连接开启开启一个线程
                newCachedThreadPool.execute(new Runnable() {

                    @Override
                    public void run() {

                        //客户端信息处理
                        messageHandler(socket);

                    }

                });

            }
        } catch (Exception e) {

            //异常处理
            e.printStackTrace();

        } finally {

            System.out.println("服务器关闭...");

            //关闭Socket服务
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }

    /**
     * 客户端信息处理方法
     * @param socket
     */
    public static void messageHandler(Socket socket) {

        //创建byte数组
        byte[] bytes = new byte[1024];

        //创建输入流
        InputStream inputStream = null;

        try {

            //获取输入流
            inputStream = socket.getInputStream();

            //无限循环,等待客户端发送消息来
            while (true) {

                //读取客户端发送过来的消息写入byte数组
                int read = inputStream.read(bytes);

                if (read != -1) {

                    //byte数组转字符串,输出客户端发送来的消息
                    System.out.println(new String(bytes, 0, read));

                } else {

                    break;

                }
            }
        } catch (Exception e) {

            //异常处理
            e.printStackTrace();

        } finally {

            System.out.println("关闭与客户端的连接...");

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }


}

(2)BIO 客户端

import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class BIOClient {

    public static void main(String[] args) {


        String username = "张三 : ";

        //创建socket
        Socket socket = null;

        //创建输入流
        OutputStream outputStream = null;

        try {

            System.out.println("连接服务器...");

            //客户端连接服务器
            socket = new Socket("127.0.0.1", 6666);

            System.out.println("服务器已连接");

            //键盘输入对象
            Scanner scanner = new Scanner(System.in);

            System.out.println("请输入信息:");

            while (scanner.hasNext()){

                //输入信息
                String message = scanner.nextLine();

                //获取输出流
                outputStream = socket.getOutputStream();

                message = username + message;

                //信息转byte数组
                byte[] bytes = message.getBytes(StandardCharsets.UTF_8);

                //向客户端发送信息
                outputStream.write(bytes);

                System.out.println("请输入信息:");

            }
        } catch (Exception e){

            //异常处理
            e.printStackTrace();

        } finally {


            System.out.println("关闭与服务器端的连接...");

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }
}

二、Java NIO 案列

1、NIO读取文件
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ReadFileNIO {

    public static void main(String[] args) {

        //创建读取的文件对象
        File file = new File("NIO.txt");

        //创建输入流
        FileInputStream fileInputStream = null;

        //创建文件通道
        FileChannel fileChannel = null;

        try {

            //实列化输入流
            fileInputStream = new FileInputStream(file);

            //根据输入流获取通道
            fileChannel = fileInputStream.getChannel();

            //创建byte缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            //循环读取通道中的数据
            while (true) {

                //清空缓冲区
                byteBuffer.clear();

                //将通道中的数据写入到缓冲区
                int read = fileChannel.read(byteBuffer);

                //通道数据读取完毕,退出循环
                if (read == -1) {
                    break;
                }

                //切换缓冲区模式(读)
                byteBuffer.flip();

                //输出缓冲区数据
                System.out.println(new String(byteBuffer.array(), 0, read));
            }

        } catch (Exception e) {

            //异常处理
            e.printStackTrace();

        } finally {

            //通道和流关闭
            if (fileChannel != null) {
                try {
                    fileChannel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        
    }

}
2、NIO写文件
package com.dashu.netty.demo.nio;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class WriteFileBIO {

    public static void main(String[] args) {

        //创建写入文本
        String txt = "同步非阻塞,服务器实现模式为一个线程处理多个连接请求。即客户端发送的连接请求都会注册到多路复用器上,多轮复用器轮询到连接有I/O请求的就进行处理";

        //创建输出文件对象
        File file = new File("NIO.txt");

        //创建输出流
        FileOutputStream fileOutputStream = null;

        //创建通道
        FileChannel fileChannel = null;

        try {

            //创建文件输出流
            fileOutputStream = new FileOutputStream(file);

            //通过文件输出流获取通道
            fileChannel = fileOutputStream.getChannel();

            //创建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            
            //缓冲区写入数据
            byteBuffer.put(txt.getBytes(StandardCharsets.UTF_8));

            //缓冲区切换模式(读)
            byteBuffer.flip();
            
            //将缓冲区的数据写入通道
            fileChannel.write(byteBuffer);

        } catch (Exception e) {

            //异常处理
            e.printStackTrace();

        } finally {

            //通道和流关闭
            if (fileChannel != null) {
                try {
                    fileChannel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }

}

3、NIO文件拷贝

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

public class ReadWriteFileNIO {

    public static void main(String[] args) {

        //源文件
        File inputFile = new File("NIO.txt");

        //目标文件
        File outputFile = new File("NIO2.txt");

        //文件输入流
        FileInputStream fileInputStream = null;

        //文件输出流
        FileOutputStream fileOutputStream = null;

        //输入流通道
        FileChannel inputFileChannel = null;

        //输出流通道
        FileChannel outputFileChannel = null;

        try {

            //文件输入流实例化
            fileInputStream = new FileInputStream(inputFile);

            //文件输出流实例化
            fileOutputStream = new FileOutputStream(outputFile);

            //输入通道实例化
            inputFileChannel = fileInputStream.getChannel();

            //输出通道实例化
            outputFileChannel = fileOutputStream.getChannel();

            //创建缓存区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            //循环读取输入通道中的数据写入到缓存区,再将缓冲区中的数据写入到输出通道中
            while (true) {

                //缓冲区清除
                byteBuffer.clear();

                //读取输入通道中的数据
                int read = inputFileChannel.read(byteBuffer);

                //判断输入通道中的数据是否读完,读完退出
                if (read == -1) {
                    break;
                }

                //切换缓冲区模式为读
                byteBuffer.flip();

                //将缓冲区中的数据写到输出通道
                outputFileChannel.write(byteBuffer);

            }
        } catch (Exception e) {

            //异常处理
            e.printStackTrace();

        } finally {

            //通道和流关闭
            if (outputFileChannel != null) {
                try {
                    outputFileChannel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (inputFileChannel != null) {
                try {
                    inputFileChannel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

4、NIO网络编程
(1)NIO 服务端
package com.dashu.netty.demo.nio.socket;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;


public class NIOServer {


    public static void main(String[] args) {

        //创建服务端Socket通道
        ServerSocketChannel serverSocketChannel = null;

        //创建客户端Socket通道
        SocketChannel socketChannel = null;

        try {
            //创建(打开)服务端Socket通道
            serverSocketChannel = ServerSocketChannel.open();

            //创建网络Socket地址
            InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

            //服务端socket绑定网络地址
            serverSocketChannel.socket().bind(inetSocketAddress);

            //设置服务端Socket通道为非阻塞
            serverSocketChannel.configureBlocking(false);

            //创建Selector选择器对象
            Selector selector = Selector.open();

            //将服务端Socket通道注册到Selector选择器上,关心的事件为  SelectionKey.OP_ACCEPT   接收
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);


            System.out.println("启动服务器成功...");
            System.out.println("等待客户端连接...");

            //无限循环,等待连接
            while (true) {

                /**
                 selector.select()  有阻塞的行为,没有客户端连接,就跳过这次循环;有客户连接,继续往下走
                 等于 0 ,无连接
                 大于0,有连接
                 */
                if (selector.select() == 0) {
                    continue;
                }

                //通过 selectedKeys 反向获取通道
                Set<SelectionKey> selectionKeySet = selector.selectedKeys();

                //迭代器遍历通道
                Iterator<SelectionKey> selectionKeyIterator = selectionKeySet.iterator();

                //循环遍历
                while (selectionKeyIterator.hasNext()) {

                    //获取SelectionKey
                    SelectionKey selectionKey = selectionKeyIterator.next();

                    //如果是OP_ACCEPT,有新的客户连接
                    if (selectionKey.isAcceptable()) {

                        //获取客户端通道
                        socketChannel = serverSocketChannel.accept();

                        System.out.println("客户端连接成功... socketChannel = " + socketChannel.hashCode());

                        //将客户端通道设为非阻塞
                        socketChannel.configureBlocking(false);

                        //将客户端通道注册到selector选择器上,并关注事件  OP_READ  读,并为通道绑定一个缓冲区
                        socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));


                    }

                    //如果是OP_READ,有新的读消息
                    if (selectionKey.isReadable()) {

                        //通过 selectionKey 获取到客户端通道
                        socketChannel = (SocketChannel) selectionKey.channel();

                        //通过 selectionKey 获取到客户端通道的缓冲区
                        ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();

                        //将客户端通道上的信息读到缓冲区
                        socketChannel.read(byteBuffer);

                        //输出信息
                        System.out.println("客户端" + socketChannel.hashCode() + "发来信息:" + new String(byteBuffer.array(), 0, byteBuffer.position()));
                    }

                    //从集合中移除当前selectionKey,防止重复操作
                    selectionKeyIterator.remove();

                }

            }
        } catch (Exception e) {

            //异常处理
            e.printStackTrace();

        } finally {

            //通道关闭
            if (socketChannel != null) {
                try {
                    socketChannel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (serverSocketChannel != null) {
                try {
                    serverSocketChannel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }

}

(2)NIO 客户端
package com.dashu.netty.demo.nio.socket;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;


public class NIOClient {

    public static void main(String[] args) {

        //创建客户端网络通道
        SocketChannel socketChannel = null;

        try {

            //创建(打开)客户端网络通道
            socketChannel = SocketChannel.open();

            //设置非阻塞
            socketChannel.configureBlocking(false);

            //创建网络Socket地址
            InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

            //连接服务器
            boolean flag = socketChannel.connect(inetSocketAddress);

            //判断连接服务器未连接
            if (!flag) {

                //判断连接服务器是否成功,没有成功,打印信息,成功后,继续执行
                while (!socketChannel.finishConnect()) {
                    System.out.println("因为连接需要事件,客户端不会阻塞,可以做其他工作");
                }

                System.out.println("连接服务器成功...");

            }

            //服务器连接成功

            //键盘输入
            Scanner scanner = new Scanner(System.in);

            //创建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            System.out.println("请输入请求服务器的信息:");

            //循环输入
            while (scanner.hasNext()) {

                //输入信息
                String message = scanner.nextLine();

                //清空缓冲区
                byteBuffer.clear();

                //缓冲区添加数据
                byteBuffer.put(message.getBytes(StandardCharsets.UTF_8));

                //切换缓冲区模式,读
                byteBuffer.flip();

                //将缓冲区的数据写入通道
                socketChannel.write(byteBuffer);

                System.out.println("请输入请求服务器的信息:");

            }

        } catch (Exception e) {

            //异常处理
            e.printStackTrace();

        } finally {

            //通道关闭
            if (socketChannel != null) {
                try {
                    socketChannel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }


    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大树下躲雨

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

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

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

打赏作者

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

抵扣说明:

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

余额充值