每日一词——IO + NIO + NIO2
大家都干了什么事情
IO
以字节、字符为单位进行低逼格的处理:通过InputStream || Reader 连接 source,通过 OutoutStream || Writer 连接 destination
NIO
以 缓存 为单位进行高逼格的处理:通过 Chanel 连接 source 及 destination
NIO2
对文件系统进行了封装,开发者只需要使用抽象的接口,其内部实现交给各个文件系统的厂商来实现,所以 java 的包分两类,一类供开发者使用:java.nio.file, java.nio.file.attribute,一类供厂商使用:java.nio.file.spi
3段代码演示其核心思想(其实也可以看出来他们的确是越来越看起来简单)
IO核心代码
public static void save(Reader src, Writer dest) {
try(Reader input = src;Writer output = dest) {
int length = -1;
char[] data = new char[1024];
while ((length = input.read(data)) != -1)
output.write(data, 0, length);
} catch (IOException e) {
logger.info("错误信息:{}", e.getMessage());
}
}
NIO核心代码块
public void dump(ReadableByteChannel src, WritableByteChannel dest) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
try(ReadableByteChannel srcCH = src; WritableByteChannel destCH = dest) {
buffer.flip(); // position = 0; limit = buffer当前元素数量
destCH.write(buffer);
buffer.clear(); // postion = 0; limit = buffer容量
} catch (IOException e) {
logger.info(e.getMessage());
}
}
不难看出,IO相比较NIO,多了一个 int length, 记录每次有多少元素被读到
NIO2 核心代码
1、操作路径:Path path = Path.get(System.getProperty(“user.home”, “Document”, “Downloads”);
2、属性读取:BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
3、属性赋值:Files.setAttribute(Paths.get(“C:\workspace\Main.java”, “basic:lastModifiedTime”, FileTime.fromMillis(System.currentTimeMillis()));
4、操作文档:
1)Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING
2)BufferedReader reader = Files.newBufferedReader(filePath, “UTF-8”);
instead of
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file, “UTF-8”)));
Path: An object that may be used to locate a file in a file system.
DirectoryStream: A directory stream allows for the convenient use of the for-each construct to iterate over adirectory.
FileSystem: This class defines the {@link #getDefault getDefault} method to get the default file system and factory methods to construct other types of file systems.
Files: This class consists exclusively of static methods that operate on files, directories, or other types of files.