Java NIO读写TXT文件(FileChannel)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29777207/article/details/86105467

先上代码为敬

代码中编码写成GBK是因为windows默认新建txt的时候是GBK格式,如果你的txt文件为UTF-8则修改为UTF-8

package channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileChannelUtil {
	/**
	 * 读取txt文件
	 */
	@SuppressWarnings("resource")
	public static void readTxt() {
		try {
			
			
			//定义缓冲区对象
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			
			//通过文件输入流获取文件通道流对象
			FileChannel inFc = new FileInputStream("C:\\test.txt").getChannel();
			
			//读取数据
			buffer.clear();
			
			int length = inFc.read(buffer);
			
			System.out.println(new String(buffer.array(),0,length,"GBK"));
			
			inFc.close();
			
		}catch(Exception e) {
			
			e.printStackTrace();
			
		}
	}

	/**
	 * 写入txt 文件
	 */
	@SuppressWarnings("resource")
	public static void writeTxt() {
		try {
			FileChannel outFc = new FileOutputStream("C:\\test.txt",true).getChannel();
			
			ByteBuffer byteBuffer = ByteBuffer.wrap("\r\n李白乘舟将欲行".getBytes("GBK"));
			
			outFc.write(byteBuffer);
			
			outFc.close();
		}catch(Exception e) {
			
		}
	}
	
	public static void main(String[] args) {
		readTxt();
		writeTxt();
	}

}

猜你喜欢

转载自blog.csdn.net/qq_29777207/article/details/86105467