NIO读写文件,简单Util直接拿去用
java.nio全称java non-blocking IO,是指jdk1.4 及以上版本里提供的新api(New IO) ,为所有的原始类型(boolean类型除外)提供缓存支持的数据容器,使用它可以提供非阻塞式的高伸缩性网络。
Java IO和NIO之间第一个最大的区别是,IO是面向流的,NIO是面向缓冲区的。
GitHub: link. 欢迎star
@Slf4j
public class NIOUtil {
/**
* 读文件返回String
*
* @param path 文件路径
* @return 读取内容
*/
public static String readFile(String path) {
String string = null;
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(path, "rw");
FileChannel channel = randomAccessFile.getChannel();
ByteBuffer allocate = ByteBuffer.allocate(1024 << 4); //16KB缓冲区
List<Byte> byteList = new ArrayList<>();
byte[] array;
int length;
while ((length = channel.read(allocate)) != -1) {
array = allocate.array();
for (int i = 0; i < length; i++) {
byteList.add(array[i]);
}
allocate.clear();
}
channel.close();
byte[] arr = new byte[byteList.size()];
for (int i = 0; i < byteList.size(); i++) {
arr[i] = byteList.get(i);
}
string = new String(arr, StandardCharsets.UTF_8);
} catch (Exception e) {
log.error("readFile failure!! error={} message={}", e, e.getMessage());
e.printStackTrace();
} finally {
if (null != randomAccessFile) {
try {
randomAccessFile.close();
} catch (IOException e) {
log.error("randomAccessFile.close() failure!! error={} message={}", e, e.getMessage());
}
}
}
return string;
}
/**
* String写文件
*
* @param text 内容
* @param path 目标文件路径
*/
public static void writeFile(String text, String path) {
RandomAccessFile randomAccessFile = null;
try {
Files.deleteIfExists(Paths.get(path)); //目标文件存在先删除
randomAccessFile = new RandomAccessFile(path, "rw");
FileChannel channel = randomAccessFile.getChannel();
channel.write(ByteBuffer.wrap(text.getBytes(StandardCharsets.UTF_8)));
channel.close();
} catch (Exception e) {
log.error("writeFile failure!! error={} message={}", e, e.getMessage());
e.printStackTrace();
} finally {
if (null != randomAccessFile) {
try {
randomAccessFile.close();
} catch (IOException e) {
log.error("randomAccessFile.close() failure!! error={} message={}", e, e.getMessage());
}
}
}
}
}
GitHub: link. 欢迎star