日期:2014-05-16  浏览次数:20888 次

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:\\Users\\liuyuan\\Desktop\\ant.txt",
					"r");
			out = new RandomAccessFile("C:\\Users\\liuyuan\\Desktop\\copy.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();
				}
			}
		}

	}
}