FileChannel之文件输入输出

1.文件的输入。

文件->读到文件流->文件通道->映射到内存->写入一个字符数组

File->FileInputStream->FileChannel->MappedByteBuffer->data[]


package IO_Operation;

import java.io.File;
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {
	public static void main(String[] args)throws Exception {
		File file = new File("d:"+File.separator+"users.txt");
		FileInputStream input = null; //文件输入流
		input = new FileInputStream(file);
		FileChannel fin = null; //输入的通道对象
		fin = input.getChannel();
		MappedByteBuffer mbb = null; //文件的内存映射
		mbb = fin.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
		byte data[] = new byte[(int)file.length()];
		int foot = 0;
		while (mbb.hasRemaining()) {
			data[foot++] = mbb.get();
		}
		System.out.println(new String(data));
		fin.close();
		input.close();
	}
}
 
 


2.文件的输出

新建一个文件->文件输出流->得到文件输出通道->开辟buf->向buf写数据->文件输出管道输出buf

package IO_Operation;

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

public class FileChannelDemo2 {
	public static void main(String[] args) throws Exception{
		String info[] = {"aaa","bbb","ccc","ddd"};//待输出的数据
		File file = new File("d:"+File.separator+"out.txt");
		FileOutputStream output = null;
		output =new FileOutputStream(file);
		FileChannel fout = null;
		fout = output.getChannel();
		ByteBuffer buf = ByteBuffer.allocate(1024);
		for (int i = 0; i < info.length; i++) {
			buf.put(info[i].getBytes());
		}
		buf.flip();
		fout.write(buf);
		fout.close();
		output.close();
	}
}



你可能感兴趣的:(FileChannel之文件输入输出)