NIO学习总结

/** 
* 使用传统的I/O读取文件内容
* @param filePath 文件路径
* @throws IOException
*/
public static void ioRead(String filePath) throws IOException {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
fis.read(b);
System.out.println(new String(b));
}

/**
* 使用NIO读取文件内容
* @param filePath 文件路径
* @throws IOException
*/
public static void nioRead(String filePath) throws IOException {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
FileChannel channel = fis.getChannel();
ByteBuffer b = ByteBuffer.allocate(1024);
channel.read(b);
byte[] by = b.array();
System.out.println(new String(by));
}

/**
* 传统I/O写文件
*
* @param filePath 文件路径
* @throws IOException
*/
public static void ioWrite(String filePath) throws IOException
{
File file = new File(filePath);
FileOutputStream fos = new FileOutputStream(file);
String[] contents = new String[] { "qian", "hao" };
for (String content : contents)
{
byte[] b = content.getBytes(Charset.forName("UTF-8"));
fos.write(b);
}
}

/**
* NIO写文件
* @param filePath 文件路径
* @throws IOException
*/
public static void nioWrite(String filePath) throws IOException
{
File file = new File(filePath);
FileOutputStream fos = new FileOutputStream(file);
// 获取文件通道
FileChannel channel = fos.getChannel();
// 设置文件缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
String[] contents = new String[] { "qian", "hao" };
// 将数据读入缓冲区中
for (String content : contents)
{
buffer.put(content.getBytes());
}
// 通道反转(将读通道转化为写通道)
buffer.flip();
// 将文件写入写通道中
channel.write(buffer);
}

/**
* 将一个文件内容复制到另外一个文件中
* @param resource 源文件路径
* @param destination 目标文件路径
* @throws IOException
*/
public static void nioCopyFile(String resource, String destination)
throws IOException
{
// 设置文件输入流
FileInputStream fis = new FileInputStream(resource);
// 设置文件输出流
FileOutputStream fos = new FileOutputStream(destination);
// 设置输入通道
FileChannel readChannel = fis.getChannel();
// 设置输出通道
FileChannel writeChannel = fos.getChannel();
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 复制文件
while (true)
{
// 清空缓冲,使其接受新的数据
buffer.clear();
// 从输入通道中将数据写入缓冲区中
int len = readChannel.read(buffer);
// 判断是否文件已读取完成
if (len == -1)
{
break;
}
// 将缓冲区的数据些到另外一个通道,(输入通道反转到输出通道)
buffer.flip();
// 从输出通道将数据写到缓冲区,写入文件中
writeChannel.write(buffer);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值