java filechannel读取txt 乱码
用io包读取中文正确,换成NIO的就成乱码了,,publicclassNIO{privatestaticintBSIZE=1024;publicstaticvoidmai...
用io包读取中文正确,换成NIO的就成乱码了,,
public class NIO {
private static int BSIZE = 1024;
public static void main(String[] args) throws IOException {
//写文件
FileChannel fc = new FileOutputStream("f:\\aaa.txt").getChannel();
fc.write(ByteBuffer.wrap("asdasdxzcxzc放到".getBytes()));
fc.close();
// //添加文件到末尾
// fc = new RandomAccessFile("f:\\aaa.txt","rw").getChannel();
// fc.position(fc.size());
// fc.write(ByteBuffer.wrap("田间".getBytes("utf-8")));
// fc.close();
//读文件
FileChannel fc2 = new FileInputStream("f:\\aaa.txt").getChannel();
//分配缓存
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
//读入缓存区
fc2.read(buff);
buff.flip();
while(buff.hasRemaining()){
System.out.print(buff.get() + " ");
}
fc2.close();
}
} 展开
public class NIO {
private static int BSIZE = 1024;
public static void main(String[] args) throws IOException {
//写文件
FileChannel fc = new FileOutputStream("f:\\aaa.txt").getChannel();
fc.write(ByteBuffer.wrap("asdasdxzcxzc放到".getBytes()));
fc.close();
// //添加文件到末尾
// fc = new RandomAccessFile("f:\\aaa.txt","rw").getChannel();
// fc.position(fc.size());
// fc.write(ByteBuffer.wrap("田间".getBytes("utf-8")));
// fc.close();
//读文件
FileChannel fc2 = new FileInputStream("f:\\aaa.txt").getChannel();
//分配缓存
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
//读入缓存区
fc2.read(buff);
buff.flip();
while(buff.hasRemaining()){
System.out.print(buff.get() + " ");
}
fc2.close();
}
} 展开
2个回答
展开全部
原先用BufferedReader b=new BufferedReader(new FileReader(path));的时候遇到中文的话会产生乱码;
代码改为:
InputStreamReader read = new InputStreamReader(new FileInputStream(path), "GB2312");
BufferedReader br = new BufferedReader(read);
后问题解决
你可以参考下
代码改为:
InputStreamReader read = new InputStreamReader(new FileInputStream(path), "GB2312");
BufferedReader br = new BufferedReader(read);
后问题解决
你可以参考下
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询