package com.example.lib;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.*;
import java.nio.charset.Charset;
public class MyClass {
public static void main(String[] args) throws IOException {
FileInputStream fs; //定义流对象变量
fs = new FileInputStream("/Users/mac/AndroidStudioProjects/MyApplication/lib/src/main/java/com/example/lib/mytext.txt");
byte[] bytes = new byte[fs.available()]; //定义接收数据的字节数组,并用流对象初始化数组大小
fs.read(bytes); //装载数据
char[] w = getChars(bytes);//将字节数组转化为字符数组,注意数组末尾会有空字符
String s = new String(w); //利用字符串
构造函数来构造字符串,
System.out.println("结果为:"+s.trim());输出时,去掉末尾空格字符
}
private static byte[] getBytes (char[] chars) {
Charset cs = Charset.forName ("UTF-8");//设定
字符集编码代号
CharBuffer cb = CharBuffer.allocate (chars.length);//按照字符数组长度进行分配空间
cb.put (chars); //装载数据
cb.flip (); //指针复位
//按照编码规则进行编码
ByteBuffer bb = cs.encode (cb);
return bb.array();
}
private static char[] getChars (byte[] bytes) {
Charset cs = Charset.forName ("UTF-8");//指定字符集编码
ByteBuffer bb = ByteBuffer.allocate (bytes.length);
bb.put (bytes);//装载数据
bb.flip ();//调整回指针为0
CharBuffer cb = cs.decode (bb);//按照指定字符集进行解码
return cb.array();//返回字符数组
}
}