shell脚本定期删除日志文件 |
您所在的位置:网站首页 › 四秒内的含义 › shell脚本定期删除日志文件 |
使用java NIO FileChannel读取文件并解决中文乱码问题
LJW_WEB: 还是老哥这个稳妥,踩了好几个坑,乱码、中文丢数据、才在这里跳过去了 使用java NIO FileChannel读取文件并解决中文乱码问题
Zeit丶浅白:
确实优雅又简单许多,多谢 gzz_gzz: 这样是不是稍微的优雅一点点 [code=java] public class FileChannelTest { public static void main(String[] args) throws IOException { RandomAccessFile raFile = new RandomAccessFile("d:/soft/AsyncFileChannelDemo.java", "rw"); FileChannel fChannel = raFile.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(32); CharBuffer charBuffer = CharBuffer.allocate(32); while ((fChannel.read(byteBuffer)) != -1) { byteBuffer.flip(); StandardCharsets.UTF_8.newDecoder().decode(byteBuffer, charBuffer, true); charBuffer.flip(); while (charBuffer.hasRemaining()) { // System.out.print("--"); System.out.print(charBuffer.get()); } byteBuffer.compact(); charBuffer.clear(); } raFile.close(); } } [/code] 使用java NIO FileChannel读取文件并解决中文乱码问题半世沁心: 说的对,可以调用compact()方法,不使用clear()方法 [code=java] public static void main(String[] args) throws IOException { Charset charset = StandardCharsets.UTF_8; CharsetDecoder decoder = charset.newDecoder(); RandomAccessFile aFile = new RandomAccessFile("D:\\Code\\oneself\\netty\\src\\main\\resources\\nio-data.text", "rw"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(32); CharBuffer cuf = CharBuffer.allocate(32); int bytesRead = inChannel.read(buf); while (bytesRead != -1) { buf.flip(); decoder.decode(buf,cuf,true); cuf.flip(); char[] chars = new char[cuf.length()]; cuf.get(chars,0,cuf.length()); System.out.println(new String(chars)); buf.compact();//(该方法清除被读取的缓冲区,没有读取的会放在缓冲区首部) cuf.clear(); bytesRead = inChannel.read(buf); } aFile.close(); } [/code] Ubuntu18.04虚拟机桥接模式连wifi并配置静态IP格子er: 配置静态ip前可以上网,配置完就上不了网了 |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |