Buffer是一个抽象类,位于java.nio包中,主要用作缓冲区。注意:Buffer是非线程安全类。

缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存。这块内存被包装成NIO Buffer对象,并提供了一组方法,用来方便的访问该块内存。

NIO 有以下几种Buffer类型:

  • ByteBuffer
  • MappedByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • ShortBuffer

一、属性
Buffer有四个基本属性:
1、capacity:  容量,buffer能够容纳的最大元素数目,在Buffer创建时设定并不能更改
2、limit: buffer中有效位置数目
3、position: 下一个读或者写的位置
4、mark:  用于记忆的标志位,配合reset()使用,初始值未设定,调用mark后将当前position设为值

属性的关系与图解 见:https://blog.csdn.net/u013096088/article/details/78638245

标记、位置、限制和容量值遵守以下不变式:
0 <= 标记mark <= 位置position <= 限制limit <= 容量capacity

二、API  
public final int capacity( ) 返回此缓冲区的容量。
public final int position() 返回此缓冲区的位置。
public final Buffer position(int newPosition) 设置此缓冲区的位置。如果mark已定义且大于新的位置,则丢弃该标记。
public final int limit( ) 返回此缓冲区的限制。
public final Buffer limit (int newLimit) 设置此缓冲区的限制。
public final Buffer mark( ) 在此缓冲区的位置设置标记。
public final Buffer reset( ) 将此缓冲区的位置重置为以前mark的位置。
public final Buffer clear( ) 清除此缓冲区。将position设置为 0,将limit设置为容量,并丢弃mark。
public final Buffer flip( ) 为读做好准备。它将limit设置为当前位置,然后将position设置为 0。如果已定义了标记,则丢弃该标记。
public final Buffer rewind( ) 一般flip()只能被执行一次,想第二次执行flip(),请使用rewind()。它使limit保持不变,将position设置为 0 ,并丢弃mark。
public final int remaining( ) 返回当前位置与限制之间的元素数,即还未读出的字节数。
public final boolean hasRemaining( ) 告知在当前位置和限制之间是否有元素。
public abstract boolean isReadOnly( ) 告知此缓冲区是否为只读缓冲区。

public abstract ByteBuffer compact();压缩数据

注释:

  • 由于ByteBuffer是非线程安全的,所以多线程访问的时候也必须加锁。

  • ByteBuffer在内部也是利用byte[]作为内存缓冲区,只不过多提供了一些标记变量而已。当多线程访问的时候,可以清楚的知道当前数据的位置。

三、操作(以ByteBuffer为例)

1、访问:
get(),从当前position位置读取
get(index),从index位置读取,不改变当前position,下面要说到的put也一样。

2、填充:
put(byte),在当前position位置填充
put(index,byte),按照绝对位置填充不改变当前position属性

3、flipping,试想,我们将填充完毕的buffer传递给socket输出,那么socket读取是依据position属性确定,就会从结尾后一位开始读,这样肯定是不正确的,如果要正确的读取我们先要:
buffer.limit(buffer.position( )).position(0);
将limit设为position, 将position设为0,这个操作就叫flipping,API直接提供了这个操作:  buffer.flip( );

特别注意:flip()方法会改变limit属性,将limit属性从capacity设置为当前position。
rewind()方法与flip()类似,但是仅将position设为0,同时取消mark标记,而不改变limit,通常用于重新读取已经被flip的buffer。
flip()另一个注意点是,两次调用buffer的flip方法,将使得position和limit属性都为0。

4、迭代取元素:

for (int i = 0; buffer.hasRemaining( ), i++) {
    myByteArray [i] = buffer.get( );
    }
     
    int count = buffer.remaining( );
    for (int i = 0; i < count, i++) {
    myByteArray [i] = buffer.get( );
    }

ByteBuffer不是线程安全的,前一种方式适合并发访问,后一种方式效率更高。这两种方式都是一个一个取,效率都比批量取低。

5.clear()方法,将buffer重设为空状态,也就是设置limit=capacity,position=0,以便重复利用。

特别注意:reset()方法和clear()方法一样用于写模式,

区别是reset()的作用是丢弃mark位置以后的数据,重新从mark位置开始写入,且mark不能未设置;而clear是从0位置开始重新写入。

6.compact()方法,用于压缩buffer,这个方法在多次重复调用时是比较低效。

compact()的作用是压缩数据。比如当前EOF是6,当前指针指向2(即0,1的数据已经写出了,没用了),那么compact方法将把2,3,4,5的数据挪到0,1,2,3的位置,然后指针指向4的位置。这样的意思是,从4的位置接着再写入数据。

7.mark(),初始是未定义的,这适合如果调用reset将抛出InvalidMarkException。调用makr()后,将当前position设为mark以便reset时返回。注意,rewind( ), clear( ), and flip( )方法都将丢弃已经创建的mark。调用limit(index),positioon(index),如果index的值小于当前mark,mark也将被丢弃。

8.比较,可以通过equals()和compateTo()方法来比较两个buffer,equals()返回boolean,compateTo()返回0,-1,1。两个buffer equal的条件是:

特别注意:equals()方法当满足下列条件时,表示两个Buffer 相等:
 1)类型相同(byte、char、int等)
 2)剩余元素的数目相等
    3)剩余元素也一一相等
equals只是比较Buffer的一部分,不是每一个在它里面的元素都比较(即它只比较Buffer中的剩余元素)。

compareTo()方法比较两个Buffer的剩余元素(byte、char等), 如果满足下列条件,则认为一个Buffer“小于”另一个Buffer:
    第一个不相等的元素小于另一个Buffer中对应的元素 。
    所有元素都相等,但第一个Buffer比另一个先耗尽(第一个Buffer的元素个数比另一个少)。

9、批量移动数据,为了更有效地进行数据传送,批量的数据存取肯定是不能少的,Buffer及其子类都有提供类似的方法,比如CharBuffer:

public CharBuffer get (char [] dst)
    public CharBuffer get (char [] dst, int offset, int length)
    public final CharBuffer put (char[] src)
    public CharBuffer put (char [] src, int offset, int length)
    public CharBuffer put (CharBuffer src)
    public final CharBuffer put (String src)
    public CharBuffer put (String src, int start, int end)

四、创建Buffer
    Buffer以及其子类都无法直接new,而必须把通过他们提供的工厂方法来创建。通常有两种方式:
1、allocate,例如
CharBuffer charBuffer = CharBuffer.allocate (100);
将在堆上分配一个可以存储100个字符的数组作为backing store。

2、wrap,包装一个已有的数组:
char [] myArray = new char [100];
CharBuffer charbuffer = CharBuffer.wrap (myArray);
注意,这样的方式创建的Buffer,将不会在堆上创建新的数组,而是直接利用myArray做backing store,这意味着任何对myArray或者buffer的修改都将影响到buffer或者myArray。可以通过public final boolean hasArray( )方法来判断是否拥有一个数组,通过array()方法取得这个数组。

五、复制Buffer
   其实这个复制也是“浅拷贝”,通过duplicate()方法将返回一个新创建的buffer,这个新buffer与原来的Buffer共享数据,一样的capacity,但是有自己的position、limit和mark属性。通过asReadOnlyBuffer()方法复制的buffer与duplicate()类似,但是是只读的,不能调用put。比较特别的是slice()方法,故名思议,类似切割一个Buffer出来,与duplicate类似,但是它将从原来Buffer的当前position开始,并且capacity等于原来Buffer的剩余元素数目,也就是(limit-position)。

示例:

1、读写操作

 package com.example.nio;

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel; /**
* 读写操作
*/
public class ReadWriteDemo {
private static final int SIZE = 1024; public static void main(String[] args) throws Exception {
String filePath; filePath = writeTest();
readTest(filePath); filePath = writeTest2();
readTest(filePath);
}
//注意:buffer.flip();一定得有,如果没有,就是从文件最后开始读取的,当然读出来的都是byte=0时候的字符。
// 通过buffer.flip();这个语句,就能把buffer的当前位置更改为buffer缓冲区的第一个位置。 public static String writeTest() {
String filePath = "C:\\Users\\use\\Desktop\\111.txt";
// 获取通道,该通道允许写操作 try (
FileChannel fc = new FileOutputStream(filePath).getChannel();
) {
String data = "1234##";
// 将字节数组包装到缓冲区中
fc.write(ByteBuffer.wrap(data.getBytes()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return filePath; } public static String writeTest2() {
// 随机读写文件流创建的管道
String filePath = "C:\\Users\\use\\Desktop\\222.txt";
String data = "abcd##";
try {
FileChannel fc = new RandomAccessFile(filePath, "rw").getChannel();
// fc.position()计算从文件的开始到当前位置之间的字节数
System.out.println("此通道的文件位置:" + fc.position());
// 设置此通道的文件位置,fc.size()此通道的文件的当前大小,该条语句执行后,通道位置处于文件的末尾
fc.position(fc.size());
// 在文件末尾写入字节
fc.write(ByteBuffer.wrap(data.getBytes()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
} public static void readTest(String filePath) { // 用通道读取文件 try (
FileChannel fc = new FileInputStream(filePath).getChannel();
) { ByteBuffer buffer = ByteBuffer.allocate(SIZE);
int len;
// 将文件内容读到指定的缓冲区中
while ((len = fc.read(buffer)) != -1) {
// 注意先调用flip方法反转Buffer,再从Buffer读取数据
buffer.flip();//此行语句一定要有 // 有几种方式可以操作ByteBuffer
// // 1.可以将当前Buffer包含的字节数组全部读取出来
// byte[] bytes = buffer.array();
// System.out.println("========方法1:bytes = " + bytes);
// System.out.println(new String(bytes));
//
// // 2.类似与InputStrean的read(byte[],offset,len)方法读取
// buffer.get(bytes, 0, len);
// System.out.println("========方法2:bytes = " + new String(bytes, 0, len)); // 3.也可以遍历Buffer读取每个字节数据
// 一个字节一个字节打印在控制台,但这种更慢且耗时
System.out.println("========方法3:一个字节一个字节打印");
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
// 最后注意调用clear方法,将Buffer的位置回归到0
buffer.clear();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
}

读写操作

2、数据转移操作(复制操作)

 package com.example.nio;

 import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel; /**
* 数据转移操作(复制操作)
*/
public class TransferDemo {
public static void main(String[] args) {
String filePath = "C:\\Users\\use\\Desktop\\test.txt";
// initBigFile(filePath);
System.out.println(String.format("===>文件大小:%s 字节", new File(filePath).length())); // 普通Java IO 缓冲流读取
transferTest2(filePath);
//普通 NIO
transferTest1(filePath);
} public static void initBigFile(String filePath) { try (FileOutputStream outputStream = new FileOutputStream(filePath);) { File file = new File(filePath);
if (!file.exists()) {
file.mkdir();
}
long size = 100 * 1024 * 1024;//100M
String data =
"111111111111111111111111111111111测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"22222222222222222222222222222222222222222222张三张三张三张三张三张三张三张三张三bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" +
"33333333333333333333333333333333测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试cccccccccccccccccccccccccccccccccccccccccccc"; while (file.length() < size) {
outputStream.write(data.getBytes());
}
System.out.println(String.format("===>文件大小:%s 字节", file.length()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 普通 NIO transfer
*
* @param filePath
*/
public static void transferTest1(String filePath) {
String descPath = "C:\\Users\\use\\Desktop\\test1.txt";
long start = System.currentTimeMillis();
try (
FileChannel fromChannel = new RandomAccessFile(filePath, "rw").getChannel();
FileChannel toChannel = new RandomAccessFile(descPath, "rw").getChannel();
) {
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(String.format("===>普通 NIO 读取并打印文件耗时:%s毫秒", System.currentTimeMillis() - start));
} /**
* 普通Java IO 缓冲流读取
*
* @param filePath
*/
public static void transferTest2(String filePath) {
String descPath = "C:\\Users\\use\\Desktop\\test2.txt";
long start = System.currentTimeMillis();
try (
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(descPath));
) {
int len;
while ((len = inputStream.read()) != -1) {
outputStream.write(len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} System.out.println(String.format("===>普通Java IO 读取并打印文件耗时:%s毫秒", System.currentTimeMillis() - start));
}
}

数据转移操作(复制操作)

3、流读取比较

 package com.example.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
* 但通道和流还是有区别,比如流只能是单向读或写,而通道可以异步读写
*/
public class FileChannelTest { // 110M
private static String file = "C:\\Users\\use\\Desktop\\111.txt"; public static void main(String[] args) throws IOException {
// 每次读取字节数
int allocate = 1024; // 普通 NIO 读取
readByChannelTest(allocate); // 28151毫秒 // // 普通 NIO 读取
// // 每次读取1个字节,每次读取1个字节太慢了
// readByChannelTest(1); // 使用内存映射文件来读取
// 从FileChannel拿到MappedByteBuffer,读取文件内容
readByChannelTest3(allocate); // 61毫秒,甚至不到100毫秒 // 对于一个只有110M的文件,验证使用FileChannel映射得到MappedByteBuffer
// 就能大幅提交文件读取速度 // 普通的缓冲流读取
readByBufferdStream(allocate); // 3922毫秒
} /**
* 使用FileChannel读取文件,并打印在控制台
*
* @param allocate 每次读取多少个字节
* @throws IOException
*/
public static void readByChannelTest(int allocate) throws IOException {
long start = System.currentTimeMillis();
FileInputStream fis = new FileInputStream(file); // 1.从FileInputStream对象获取文件通道FileChannel
FileChannel channel = fis.getChannel();
long size = channel.size(); // 2.从通道读取文件内容
byte[] bytes = new byte[allocate];
ByteBuffer byteBuffer = ByteBuffer.allocate(allocate); // channel.read(ByteBuffer) 方法就类似于 inputstream.read(byte)
// 每次read都将读取 allocate 个字节到ByteBuffer
int len;
while ((len = channel.read(byteBuffer)) != -1) {
// 注意先调用flip方法反转Buffer,再从Buffer读取数据
byteBuffer.flip(); // 有几种方式可以操作ByteBuffer
// 1.可以将当前Buffer包含的字节数组全部读取出来
bytes = byteBuffer.array();
// System.out.print(new String(bytes)); // 2.类似与InputStrean的read(byte[],offset,len)方法读取
// byteBuffer.get(bytes, 0, len);
// System.out.print(new String(bytes, 0 ,len)); // 3.也可以遍历Buffer读取每个字节数据
// 一个字节一个字节打印在控制台,但这种更慢且耗时
// while(byteBuffer.hasRemaining()) {
// System.out.print((char)byteBuffer.get());
// } // 最后注意调用clear方法,将Buffer的位置回归到0
byteBuffer.clear(); } // 关闭通道和文件流
channel.close();
fis.close(); long end = System.currentTimeMillis();
System.out.println(String.format("\n===>文件大小:%s 字节", size));
System.out.println(String.format("===>读取并打印文件耗时:%s毫秒", end - start));
} /**
* 仍然是根据FileChannel操作ByteBuffer,从ByteBuffer读取内容
* 通道读取文件,速度比内存映射慢很多,甚至比普通缓冲流要慢
*
* @param allocate
* @throws IOException
*/
public static void readByChannelTest2(int allocate) throws IOException {
long start = System.currentTimeMillis();
FileInputStream fis = new FileInputStream(file); // 1.从FileInputStream对象获取文件通道FileChannel
FileChannel channel = fis.getChannel();
long size = channel.size(); // 每次读取allocate个字节,计算要循环读取多少次
long cycle = size / allocate;
// 看是否能整数倍读完
int mode = (int) (size % allocate); // 循环读取
byte[] bytes;
ByteBuffer byteBuffer = ByteBuffer.allocate(allocate);
for (long i = 0; i < cycle; i++) {
if (channel.read(byteBuffer) != -1) {
byteBuffer.flip();
bytes = byteBuffer.array();
// System.out.print(new String(bytes));
byteBuffer.clear();
}
} // 读取最后mode个字节
if (mode > 0) {
byteBuffer = ByteBuffer.allocate(mode);
if (channel.read(byteBuffer) != -1) {
byteBuffer.flip();
bytes = byteBuffer.array();
// System.out.print(new String(bytes));
byteBuffer.clear();
}
} // 关闭通道和文件流
channel.close();
fis.close(); long end = System.currentTimeMillis();
System.out.println(String.format("\n===>文件大小:%s 字节", size));
System.out.println(String.format("===>读取并打印文件耗时:%s毫秒", end - start));
} /**
* 通过 FileChannel.map()拿到MappedByteBuffer
* 使用内存文件映射,速度会快很多
*
* @throws IOException
*/
public static void readByChannelTest3(int allocate) throws IOException {
long start = System.currentTimeMillis(); RandomAccessFile fis = new RandomAccessFile(new File(file), "rw");
FileChannel channel = fis.getChannel();
long size = channel.size(); // 构建一个只读的MappedByteBuffer
MappedByteBuffer mappedByteBuffer = channel.map(MapMode.READ_ONLY, 0, size); // 如果文件不大,可以选择一次性读取到数组
// byte[] all = new byte[(int)size];
// mappedByteBuffer.get(all, 0, (int)size);
// 打印文件内容
// System.out.println(new String(all)); // 如果文件内容很大,可以循环读取,计算应该读取多少次
byte[] bytes = new byte[allocate];
// 每次读取allocate个字节,计算要循环读取多少次
long cycle = size / allocate;
// 看是否能整数倍读完
int mode = (int) (size % allocate);
//byte[] eachBytes = new byte[allocate];
for (int i = 0; i < cycle; i++) {
// 每次读取allocate个字节
mappedByteBuffer.get(bytes); // 打印文件内容,关闭打印速度会很快
// System.out.print(new String(bytes));
}
if (mode > 0) {
bytes = new byte[mode];
mappedByteBuffer.get(bytes); // 打印文件内容,关闭打印速度会很快
// System.out.print(new String(bytes));
} // 关闭通道和文件流
channel.close();
fis.close(); long end = System.currentTimeMillis();
System.out.println(String.format("\n===>文件大小:%s 字节", size));
System.out.println(String.format("===>读取并打印文件耗时:%s毫秒", end - start));
} /**
* 普通Java IO 缓冲流读取
*
* @throws IOException
*/
public static void readByBufferdStream(int allocate) throws IOException {
long start = System.currentTimeMillis();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
long size = bis.available(); int len = 0;
byte[] eachBytes = new byte[allocate];
while ((len = bis.read(eachBytes)) != -1) {
// System.out.print(new String(eachBytes, 0, len));
} bis.close(); long end = System.currentTimeMillis();
System.out.println(String.format("\n===>文件大小:%s 字节", size));
System.out.println(String.format("===>读取并打印文件耗时:%s毫秒", end - start));
} }

流读取比较

4、内存映射

 package com.example.nio;

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Scanner; /**
* 内存映射
*/
public class MapDemo {
public static void main(String[] args) { // 从标准输入获取数据
System.out.println("请输入:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
byte[] bytes = str.getBytes(); String filePath = "C:\\Users\\use\\Desktop\\mapTest.txt";
try {
FileChannel fileChannel = new RandomAccessFile(filePath, "rw").getChannel();
// 获取内存映射缓冲区,并向缓冲区写入数据
//追加
MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, fileChannel.size(), bytes.length);
byteBuffer.put(bytes); // 再次打开刚刚的文件,读取其中的内容
FileChannel channel = new FileInputStream(filePath).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024);
System.out.println("文件内容:");
while (channel.read(buffer) != -1) {
// 注意先调用flip方法反转Buffer,再从Buffer读取数据
buffer.flip();//此行语句一定要有
System.out.print(new String(buffer.array()));
}
System.out.println(""); } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("");
}
}

内存映射

5、中文乱码问题

 package com.example.nio;

 import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; /**
* 中文乱码问题
*/
public class EnCodeDemo { public static void main(String args[]) throws Exception { int bufSize = 1000000;//一次读取的字节长度
String filePath = "C:\\Users\\use\\Desktop\\test.txt";
File fin = new File(filePath);//读取的文件
String descPath = "C:\\Users\\use\\Desktop\\test_copy.txt";
File fout = new File(descPath);//写出的文件
Date startDate = new Date();
FileChannel fcin = new RandomAccessFile(fin, "r").getChannel();
ByteBuffer rBuffer = ByteBuffer.allocate(bufSize); FileChannel fcout = new RandomAccessFile(fout, "rws").getChannel(); readFileByLine(bufSize, fcin, rBuffer, fcout);
Date endDate = new Date(); System.out.print(startDate + "|" + endDate);//测试执行时间
if (fcin.isOpen()) {
fcin.close();
}
if (fcout.isOpen()) {
fcout.close();
}
} public static void readFileByLine(int bufSize, FileChannel fcin,
ByteBuffer rBuffer, FileChannel fcout) {
String enter = "\n";
List<String> dataList = new ArrayList<String>();//存储读取的每行数据
byte[] lineByte = new byte[0]; // String encode = "GBK";
String encode = "UTF-8";
try {
//temp:由于是按固定字节读取,在一次读取中,第一行和最后一行经常是不完整的行,因此定义此变量来存储上次的最后一行和这次的第一行的内容,
//并将之连接成完成的一行,否则会出现汉字被拆分成2个字节,并被提前转换成字符串而乱码的问题
byte[] temp = new byte[bufSize];
while (fcin.read(rBuffer) != -1) {//fcin.read(rBuffer):从文件管道读取内容到缓冲区(rBuffer)
int rSize = rBuffer.position();//读取结束后的位置,相当于读取的长度
byte[] bs = new byte[rSize];//用来存放读取的内容的数组
rBuffer.rewind();//将position设回0,所以你可以重读Buffer中的所有数据,此处如果不设置,无法使用下面的get方法
rBuffer.get(bs);//相当于rBuffer.get(bs,0,bs.length()):从position初始位置开始相对读,读bs.length个byte,并写入bs[0]到bs[bs.length-1]的区域
rBuffer.clear(); int startNum = 0;
int LF = 10;//换行符
int CR = 13;//回车符
boolean hasLF = false;//是否有换行符
for (int i = 0; i < rSize; i++) {
if (bs[i] == LF) {
hasLF = true;
int tempNum = temp.length;
int lineNum = i - startNum;
lineByte = new byte[tempNum + lineNum];//数组大小已经去掉换行符 System.arraycopy(temp, 0, lineByte, 0, tempNum);//填充了lineByte[0]~lineByte[tempNum-1]
temp = new byte[0];
System.arraycopy(bs, startNum, lineByte, tempNum, lineNum);//填充lineByte[tempNum]~lineByte[tempNum+lineNum-1] String line = new String(lineByte, 0, lineByte.length, encode);//一行完整的字符串(过滤了换行和回车)
dataList.add(line);
// System.out.println(line);
writeFileByLine(fcout, line + enter); //过滤回车符和换行符
if (i + 1 < rSize && bs[i + 1] == CR) {
startNum = i + 2;
} else {
startNum = i + 1;
} }
}
if (hasLF) {
temp = new byte[bs.length - startNum];
System.arraycopy(bs, startNum, temp, 0, temp.length);
} else {//兼容单次读取的内容不足一行的情况
byte[] toTemp = new byte[temp.length + bs.length];
System.arraycopy(temp, 0, toTemp, 0, temp.length);
System.arraycopy(bs, 0, toTemp, temp.length, bs.length);
temp = toTemp;
}
}
if (temp != null && temp.length > 0) {//兼容文件最后一行没有换行的情况
String line = new String(temp, 0, temp.length, encode);
dataList.add(line);
// System.out.println(line);
writeFileByLine(fcout, line + enter);
}
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 写到文件上
*
* @param fcout
* @param line
*/
@SuppressWarnings("static-access")
public static void writeFileByLine(FileChannel fcout, String line) {
try {
fcout.write(ByteBuffer.wrap(line.getBytes("UTF-8")), fcout.size());
} catch (IOException e) {
e.printStackTrace();
}
}
}

中文乱码问题

转自:

https://blog.csdn.net/u013096088/article/details/78638245

http://ifeve.com/buffers/

https://blog.csdn.net/elf8848/article/details/39926897#

https://docs.oracle.com/javase/8/docs/api/index.html

https://blog.csdn.net/v123411739/article/details/50620289

Java NIO —— Buffer(缓冲区)的更多相关文章

  1. Java NIO Buffer缓冲区

    原文链接:http://tutorials.jenkov.com/java-nio/buffers.html Java NIO Buffers用于和NIO Channel交互.正如你已经知道的,我们从 ...

  2. Java NIO ———— Buffer 缓冲区详解 入门

    引言缓冲区是一个用于特定基本类型的容器.由java.nio 包定义,所有缓冲区都是 Buffer 抽象类的子类. Java NIO 中的 Buffer ,主要用于与NIO 通道进行交互.数据从通道存入 ...

  3. Java NIO Buffer(netty源码死磕1.2)

    [基础篇]netty源码死磕1.2:  NIO Buffer 1. Java NIO Buffer Buffer是一个抽象类,位于java.nio包中,主要用作缓冲区.Buffer缓冲区本质上是一块可 ...

  4. (二:NIO系列) Java NIO Buffer

    出处:Java NIO Buffer Buffer是一个抽象类,位于java.nio包中,主要用作缓冲区.Buffer缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存.这块内存被包装成NIO ...

  5. java.nio.Buffer 中的 flip()方法

    在Java NIO编程中,对缓冲区操作常常需要使用  java.nio.Buffer中的 flip()方法. Buffer 中的 flip() 方法涉及到 Buffer 中的capacity.posi ...

  6. Java NIO之缓冲区Buffer

    Java NIO的核心部件: Buffer Channel Selector Buffer 是一个数组,但具有内部状态.如下4个索引: capacity:总容量 position:下一个要读取/写入的 ...

  7. Java NIO 之缓冲区

    缓冲区基础 所有的缓冲区都具有四个属性来 供关于其所包含的数据元素的信息. capacity(容量):缓冲区能够容纳数据的最大值,创建缓冲区后不能改变. limit(上界):缓冲区的第一个不能被读或写 ...

  8. [翻译] java NIO Buffer

    原文地址:http://tutorials.jenkov.com/java-nio/buffers.html JAVA NIO 是在和channel交互的时候使用的.正如你所知道的,数据是从chann ...

  9. Java NIO——2 缓冲区

    一.缓冲区基础 1.缓冲区并不是多线程安全的. 2.属性(容量.上界.位置.标记) capacity limit  第一个不能被读或写的元素 position  下一个要被读或写的元素索引 mark ...

随机推荐

  1. 【bzoj1485:】【 [HNOI2009]有趣的数列】模任意数的卡特兰数

    (上不了p站我要死了,侵权度娘背锅) Description 我们称一个长度为2n的数列是有趣的,当且仅当该数列满足以下三个条件: (1)它是从1到2n共2n个整数的一个排列{ai}: (2)所有的奇 ...

  2. [POI2014]Around the world

    题目大意: 一个环上有$n(n\le10^6)$个点,每个点之间的距离为$l_i(l_i\le10^9)$.有$m(m\le100)$架飞机,每架飞机单次最大航行距离为$d_i$.飞机只能在点上起飞. ...

  3. List集合-保存和输出宠物信息

    package collection; /** * 宠物类 * @author * */ public class Pet { private String name; private String ...

  4. linux coreseek-4.1安装

    1.假设已经有coreseek-4.1-beta.tar.gz源文件 [root@qp232 ~]# cd /usr/local [root@qp232 local]# tar -zxvf /yd/l ...

  5. JDBC完整版实现

    package songyan.jdbc.test; import java.sql.Connection; import java.sql.DriverManager; import java.sq ...

  6. Bluetooth篇 开发实例之七 匹配&UUID

    匹配和通信是两回事. 1.用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK中给出.但是可以通过反射来获取. 知道这两个API的 ...

  7. 如何获取Class的所有方法

    // 取得所有方法 Method[] hideMethod =Activity.class.getMethods(); int i = 0; for (; i < hideMethod.leng ...

  8. Systemd入门教程:命令篇(转)

    作者: 阮一峰 日期: 2016年3月 7日 Systemd 是 Linux 系统工具,用来启动守护进程,已成为大多数发行版的标准配置. 本文介绍它的基本用法,分为上下两篇.今天介绍它的主要命令,下一 ...

  9. top显示的内存各项参数解析

    top观察进程数据时,会有如下几个内存参数(可以用f选择显示哪些参数): VIRT, RES, SHR, SWAP, CODE, DATA top实际上是从/proc/<pid>/stat ...

  10. 使用echarts简单制作中国地图,echarts中国地图

    网站需要一张中国地图,并且鼠标经过某个省份,该省份的省份名字显示,而且该省份的地区会变色显示. 第一种方法: 将每个省份的图片定位(先隐藏),拼合成一张中国地图,然后再定位省份名称,鼠标经过省份名字, ...