Java 对象序列化 NIO NIO2详细介绍及解析
本文将从以下三个方面详细介绍Java中的对象序列化、NIO和NIO2:
- Java对象序列化
- NIO
- NIO2
Java对象序列化
Java对象序列化是指将Java对象转换为字节流,以便在网络上传输或在本地保存到文件中。
Java中的对象序列化可以通过序列化(Serialization)API来实现,包括Serializable接口和Externalizable接口。其中Serializable接口是一个标记接口,用于告诉JVM这个类是可以序列化的,而Externalizable接口则是用于自定义序列化和反序列化过程的接口。
以下是一个示例代码,将Person类对象进行序列化和反序列化,并输出结果:
import java.io.*;
public class ObjectSerializeDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person = new Person("张三", 18);
String filename = "person.obj";
// ObjectOutputStream将Person对象序列化到文件中
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.writeObject(person);
outputStream.close();
// ObjectInputStream从文件中反序列化Person对象
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(filename));
Person deserializedPerson = (Person) inputStream.readObject();
inputStream.close();
// 打印反序列化后的Person对象
System.out.println("Name: " + deserializedPerson.getName());
System.out.println("Age: " + deserializedPerson.getAge());
}
}
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
NIO
NIO(New IO)是Java 1.4中引入的新IO包,与传统IO包(或者称为IO流)相比,它有以下优点:
- 可以支持非阻塞IO
- 使用一个线程来处理多个连接,降低了线程的开销
- 使用Selector来注册连接,降低了连接的开销
以下是一个简单的NIO示例,通过ServerSocketChannel和SocketChannel来实现简单服务器和客户端通信:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NIOServerDemo {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
InetSocketAddress address = new InetSocketAddress("localhost", 9999);
serverSocketChannel.bind(address);
serverSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
int num = selector.select();
if (num == 0) {
continue;
}
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
socketChannel.read(buffer);
String message = new String(buffer.array()).trim();
System.out.println("Server receives message: " + message);
ByteBuffer response = ByteBuffer.wrap(("Server sends response: " + message).getBytes());
socketChannel.write(response);
}
iterator.remove();
}
}
}
}
NIO2
NIO2是Java 1.7中引入的新IO包,相比于NIO,它有一些新的特性:
- 异步IO,可以通过CompletionHandler回调函数处理IO操作的结果
- Path类,可以更方便地操作文件系统
- 对于非文件系统的IO,提供了AsynchronousChannel接口来支持异步操作
以下是一个简单的NIO2示例,通过AsynchronousServerSocketChannel和AsynchronousSocketChannel来实现简单的服务器和客户端通信:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class NIO2ServerDemo {
public static void main(String[] args) throws IOException {
AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open();
InetSocketAddress address = new InetSocketAddress("localhost", 9999);
serverChannel.bind(address);
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public void completed(AsynchronousSocketChannel clientChannel, Object attachment) {
serverChannel.accept(null, this);
ByteBuffer buffer = ByteBuffer.allocate(1024);
clientChannel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer buffer) {
buffer.flip();
String message = new String(buffer.array()).trim();
System.out.println("Server receives message: " + message);
ByteBuffer response = ByteBuffer.wrap(("Server sends response: " + message).getBytes());
clientChannel.write(response);
buffer.clear();
}
@Override
public void failed(Throwable exc, ByteBuffer buffer) {}
});
}
@Override
public void failed(Throwable exc, Object attachment) {}
});
while (true){}
}
}
以上是Java对象序列化、NIO和NIO2的简单介绍及示例说明。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java 对象序列化 NIO NIO2详细介绍及解析 - Python技术站