
正文
javanio实例代码 java nio实例
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
java nio bytebuffer文件读写问题
JDK1.4以后就提供java.nio的包,nio主要提供字节与字符的映射、内存映射文件和文件加锁机制
其中内存映射文件在读取大文件时可能会用上,因为内存映射不是直接把文件加载到JVM内存空间
而是借用操作系统对文件的读取,这经历了由当前Java态进入到操作系统内核态,再由操作系统读取文件,
并返回数据到当前Java态的过程。由Java态进入操作系统内核态离不开nio包中两个重要的类
FileChannel 和 ByteBuffer。FileChannel表示文件通道,可以从FileInputStream、FileOutputStream
以及RandomAccessFile对象获取文件通道,你可以从文件通道直接读取文件,也可以使用“内存映射”
即使用通道,将文件内存映射到ByteBuffer,可以映射一部分内容,也可以映射全部内容,使用内存映射
能大幅提高我们操作大文件的速度
FileChannel 和 ByteBuffer文件读取
[java] view plain copy
package nio;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
/**
*
* Channel类似与流,数据可以从Channel读取到Buffer,也可以从Buffer写入到Channel
* 但通道和流还是有区别,比如流只能是单向读或写,而通道可以异步读写
*
* @author yli
*/
public class FileChannelTest {
相关问答
Q1: JAVA用nio写CS程序,服务器端接收到的信息不完整,求助!SocketChannel,Bytebuffer
while(true){
buff.clear();
int len = sc.read(buff);
if(len ==-1){ break;}
buff.flip();
content += charset.decode(buff);
}
Q2: 利用java.nio的FileChannel能够实现按行读取文件吗?(解决了)
利用java.nio的FileChannel能够实现按行读取文件:
具体思路是:设置两个缓冲区,一大一小,大的缓冲区为每次读取的量,小的缓冲区存放每行的数据(确保大小可存放文本中最长的那行)。读取的时候判断是不是换行符13,是的话则返回一行数据,不是的话继续读取,直到读完文件。
实现方法:
FileChannel fc=raf.getChannel();
//一次读取文件,读取的字节缓存数
ByteBuffer fbb=ByteBuffer.allocate(1024*5);
fc.read(fbb);
fbb.flip();
//每行缓存的字节 根据你的实际需求
ByteBuffer bb=ByteBuffer.allocate(500);
//判断是否读完文件
public boolean hasNext() throws IOException {
if(EOF)return false;
if(fbb.position()==fbb.limit()){//判断当前位置是否到了缓冲区的限制
if(readByte()==0) return false;
}
while(true){
if(fbb.position()==fbb.limit()){
if(readByte()==0) break;
}
byte a=fbb.get();
if(a==13){
if(fbb.position()==fbb.limit()){
if(readByte()==0) break;
}
return true;
}else{
if (bb.position() bb.limit()) {
bb.put(a);
}else {
if(readByte()==0) break;
}
}
}
return true;
}
Q3: 怎么为JAVA NIO或Netty程序设置网络通信代理?
服务端
// 设置一个处理客户端消息和各种消息事件的类(Handler)bootstrap.setPipelineFactory(newChannelPipelineFactory() { @Override publicChannelPipeline getPipeline()throwsException { returnChannels.pipeline( newObjectDecoder(ClassResolvers.cacheDisabled(this .getClass().getClassLoader())), newObjectServerHandler()); }});
客户端
// 设置一个处理服务端消息和各种消息事件的类(Handler)
bootstrap.setPipelineFactory(newChannelPipelineFactory() { @Override publicChannelPipeline getPipeline()throwsException { returnChannels.pipeline(newObjectEncoder(), newObjectClientHandler()); }});
要传递对象,自然要有一个被传递模型,一个简单的Pojo,当然,实现序列化接口是必须的。
/** * @author lihzh * @alia OneCoder * @blog */public class Command implementsSerializable { privatestaticfinallongserialVersionUID = 7590999461767050471L; privateString actionName; publicString getActionName() { returnactionName; } publicvoidsetActionName(String actionName) { this.actionName = actionName; }}
服务端和客户端里,我们自定义的Handler实现如下:
ObjectServerHandler .java
/** * 对象传递服务端代码 * * @author lihzh * @alia OneCoder * @blog */public class ObjectServerHandler extendsSimpleChannelHandler { /** * 当接受到消息的时候触发 */ @Override publicvoidmessageReceived(ChannelHandlerContext ctx, MessageEvent e) throwsException { Command command = (Command) e.getMessage(); // 打印看看是不是我们刚才传过来的那个 System.out.println(command.getActionName()); }}
ObjectClientHandler .java
/** * 对象传递,客户端代码 * * @author lihzh * @alia OneCoder * @blog */public class ObjectClientHandler extendsSimpleChannelHandler { /** * 当绑定到服务端的时候触发,给服务端发消息。 * * @author lihzh * @alia OneCoder */ @Override publicvoidchannelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { // 向服务端发送Object信息 sendObject(e.getChannel()); } /** * 发送Object * * @param channel * @author lihzh * @alia OneCoder */ privatevoidsendObject(Channel channel) { Command command =newCommand(); command.setActionName("Hello action."); channel.write(command); } }
启动后,服务端正常打印结果:Hello action.
简单梳理一下思路:
通过Netty传递,都需要基于流,以ChannelBuffer的形式传递。所以,Object - ChannelBuffer.
Netty提供了转换工具,需要我们配置到Handler。
样例从客户端 - 服务端,单向发消息,所以在客户端配置了编码,服务端解码。如果双向收发,则需要全部配置Encoder和Decoder。
这里需要注意,注册到Server的Handler是有顺序的,如果你颠倒一下注册顺序:
bootstrap.setPipelineFactory(newChannelPipelineFactory() {
@Override publicChannelPipeline getPipeline()throwsException { returnChannels.pipeline(newObjectServerHandler(), newObjectDecoder(ClassResolvers.cacheDisabled(this .getClass().getClassLoader())) ); }});
结果就是,会先进入我们自己的业务,再进行解码。这自然是不行的,会强转失败。至此,你应该会用Netty传递对象了吧。
Q4: 介绍一下Java NIO,NIO读取文件都有哪些方法
NIO也就是New I/O,是一组扩展Java IO操作的API集, 于Java 1.4起被引入,Java 7中NIO又提供了一些新的文件系统API,叫NIO2.
NIO2提供两种主要的文件读取方法:
使用buffer和channel类
使用Path 和 File 类
NIO读取文件有以下三种方式:
1. 旧的NIO方式,使用BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WithoutNIOExample
{
public static void main(String[] args)
{
BufferedReader br = null;
String sCurrentLine = null;
try
{
br = new BufferedReader(
new FileReader("test.txt"));
while ((sCurrentLine = br.readLine()) != null)
{
System.out.println(sCurrentLine);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)
br.close();
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
2. 使用buffer读取小文件
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadFileWithFileSizeBuffer
{
public static void main(String args[])
{
try
{
RandomAccessFile aFile = new RandomAccessFile(
"test.txt","r");
FileChannel inChannel = aFile.getChannel();
long fileSize = inChannel.size();
ByteBuffer buffer = ByteBuffer.allocate((int) fileSize);
inChannel.read(buffer);
buffer.rewind();
buffer.flip();
for (int i = 0; i fileSize; i++)
{
System.out.print((char) buffer.get());
}
inChannel.close();
aFile.close();
}
catch (IOException exc)
{
System.out.println(exc);
System.exit(1);
}
}
}
3. 分块读取大文件
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadFileWithFixedSizeBuffer
{
public static void main(String[] args) throws IOException
{
RandomAccessFile aFile = new RandomAccessFile
("test.txt", "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(inChannel.read(buffer) 0)
{
buffer.flip();
for (int i = 0; i buffer.limit(); i++)
{
System.out.print((char) buffer.get());
}
buffer.clear(); // do something with the data and clear/compact it.
}
inChannel.close();
aFile.close();
}
}
4. 使用MappedByteBuffer读取文件
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class ReadFileWithMappedByteBuffer
{
public static void main(String[] args) throws IOException
{
RandomAccessFile aFile = new RandomAccessFile
("test.txt", "r");
FileChannel inChannel = aFile.getChannel();
MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
buffer.load();?
for (int i = 0; i buffer.limit(); i++)
{
System.out.print((char) buffer.get());
}
buffer.clear(); // do something with the data and clear/compact it.
inChannel.close();
aFile.close();
}
}
javanio实例代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java nio实例、javanio实例代码的信息别忘了在本站进行查找喔。








