NIO 中文乱码自我解决的简单DEMO


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.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.commons.lang.time.DurationFormatUtils;


public class NIOTest {
    
    public static final int SIZE = 102400;
    public static final String PATH = "D:\\test\\test.txt";
    
    public static void main(String args[]) {
        
        //方法一
        /*
         try {//写数据
            FileChannel fileOutChannel = new FileOutputStream(PATH,true).getChannel();
            fileOutChannel.write(ByteBuffer.wrap("这是用FileOutpuStream调用NIO的Channel写出的内容".getBytes()));
            System.out.println("写出成功!");
            fileOutChannel.close();
            //读数据
            FileChannel fileInChannel = new FileInputStream(PATH).getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(SIZE);
            fileInChannel.read(byteBuffer);
            byteBuffer.flip();
            Charset charset = Charset.forName("UTF-8");
            while (byteBuffer.hasRemaining()) {
                CharsetDecoder charsetDecoder = charset.newDecoder();
                CharBuffer charBuffer = charsetDecoder.decode(byteBuffer);
                System.out.print(charBuffer);                   
            }
            System.out.println();
            System.out.println("读入完成!");
            fileInChannel.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        */
        
        //方法二
        try {
             RandomAccessFile randomAccessFile = new RandomAccessFile(PATH, "rw");
            //写数据
            randomAccessFile.writeUTF("这是用RandomAccessFile调用NIO的Channel写出的内容");
            System.out.println("写出成功!");
            //读数据
            randomAccessFile.seek(0);
            System.out.println(randomAccessFile.readUTF());
            System.out.println("读入成功!");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO: handle exception
        }
        
    }
    
    
    

}

查看方法一运行效果:
1112483-20180504170709515-353295891.png

转载于:https://www.cnblogs.com/jpfss/p/8991551.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值