专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Access

NIO的应用(RandomAccessFile、Charset)

发布时间:2010-05-20 14:01:29 文章来源:www.iduyao.cn 采编人员:星星草
NIO的使用(RandomAccessFile、Charset)

 

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class test5 {
	public static void main(String[] args) {
		RandomAccessFile in = null;
		RandomAccessFile out = null;

		try {
			in = new RandomAccessFile("C:UsersliuyuanDesktopant.txt",
					"r");
			out = new RandomAccessFile("C:UsersliuyuanDesktopcopy.txt",
					"rw");

			FileChannel fci = in.getChannel();
			FileChannel fco = out.getChannel();

			MappedByteBuffer mbb = fci.map(FileChannel.MapMode.READ_ONLY, 0, in
					.length());

			Charset latin = Charset.forName("ISO-8859-1");

			CharsetDecoder decoder = latin.newDecoder();
			CharsetEncoder encoder = latin.newEncoder();

			CharBuffer cb = decoder.decode(mbb);
			ByteBuffer bb = encoder.encode(cb);

			fco.write(bb);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: