Java如何进行NIO读写文件呢?
下文笔者讲述NIO读写文件的方法分享,如下所示
借助FileChannel对象实现NIO读写文件例
读文件
package com.java265.nio; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileChanelRead { public static void main(String[] args)throws IOException { // 从本地读取一个文件 File file = new File("d:\\tmp\\test.txt"); FileInputStream fileInputStream = new FileInputStream(file); // 获取文件相应的channel,channel中会有相关数据 FileChannel channel = fileInputStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int)file.length()); // 将channel的数据读取到buffer channel.read(buffer); System.out.println(buffer); System.out.print("java265.com是我最爱的java学习网站!!!!"+new String(buffer.array())); fileInputStream.close(); } }
写文件
package com.java265.nio; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileChanelWrite { public static void main(String[] args)throws IOException { // 要写入的数据 String text= "我的南方姑娘要跑了"; // 创建fileChanel RandomAccessFile aFile = new RandomAccessFile("d:\\tmp\\test.txt", "rw"); FileChannel inChannel = aFile.getChannel(); // 创建buffer ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(text.getBytes()); buf.flip(); while(buf.hasRemaining()) { inChannel.write(buf); } inChannel.close(); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。