FileDescriptor 类
- 该类的作用?
它用作特定结构的不透明句柄,这些结构表示打开的文件、打开的套接字或其它字节源宿。它实际用途是创建一个 FileInputStream 或 FileOutputStream,应用程序不应该创建自己的文件描述符 - 在哪里被用到了?
MappedByteBuffer 中被用到, DirectByteBuffer 中又继承了 MappedByteBuffer, DirectByteBuffer 又是 NIO 的一个重要类,所以看看还是对我们理解底层有所帮助的 - 输出信息到屏幕示例代码:
@Test
void test() throws IOException {
FileOutputStream out = new FileOutputStream(java.io.FileDescriptor.out);
out.write("我会嘤嘤嘤!!!".getBytes());
out.close();
}
- standardStream(int fd) 方法
参数 fd | 代表含义 |
---|---|
0 | 标准输入流的句柄 |
1 | 标准输出流的句柄 |
2 | 标准错误流的句柄 |
-
sync() 方法,这是一个本地(native)方法
强制所有系统缓冲区与底层设备同步,该方法再将此 FileDescriptor 的所有修改数据和属性都写入相关设备返回。特别地,如果该 FileDescriptor 引用诸如文件系统中的文件的物理存储介质,同步将不会返回,直到与该 FileDescriptor 相关联的所有内存修改的副本已被写入物理介质。同步意图由需要物理存储(如文件)的代码用于已知状态,例如:提供简单事务的类可能会使用 sync 来确保由给定的文件引起的对文件的所有更改交易记录在存储介质上。sync 只影响此 FileDescriptor 下游的缓冲区。如果应用程序正在执行任何内存缓冲(例如,通过 BufferedOutputStream 对象 ),那么这些缓冲区必须在数据受同步影响之前刷新到 FileDescriptor 中(例如调用 OutputStream.flush)
/**
* Attach a Closeable to this FD for tracking.
* parent reference is added to otherParents when
* needed to make closeAll simpler.
*/
// 在此FD上附加一个壁橱以进行跟踪。 需要使closeAll更简单时,将父引用添加到otherParents中。
synchronized void attach(Closeable c) {
if (parent == null) {
// first caller gets to do this
parent = c;
} else if (otherParents == null) {
otherParents = new ArrayList<>();
otherParents.add(parent);
otherParents.add(c);
} else {
otherParents.add(c);
}
}