专栏名称: ImportNew
伯乐在线旗下账号,专注Java技术分享,包括Java基础技术、进阶技能、架构设计和Java技术领域动态等。
目录
相关文章推荐
51好读  ›  专栏  ›  ImportNew

JNI 探秘 — 你不知道的 FileInputStream 的秘密

ImportNew  · 公众号  · Java  · 2017-06-13 13:31

正文

请到「今天看啥」查看全文


security.checkRead(name);

}

if (name == null) {

throw new NullPointerException();

}

fd = new FileDescriptor();

open(name);

}


我们忽略安全管理器的检查,可以看到,在创建一个文件输入流时,主要做了两件事,一个是new一个FileDescriptor(文件描述符),一个便是调用了open方法。


不过在此之前,其实还调用了一个方法,在FileInputStream源码的下方,有这样一个静态块。


static {

initIDs();

}


它将在第一次加载FileInputStream类的时候,调用一个静态的initIDs的本地方法,这里我们不跟踪这个方法的源码,它并不是我们的重点,它的作用是设置类中(也就是FileInputStream)的属性的地址偏移量,便于在必要时操作内存给它赋值,而FileInputStream的initIDs方法只设置了fd这一个属性的地址偏移量。


接下来,我们首先看下FileDescriptor这个类是什么样子的,它的源码如下。


package java.io;

public final class FileDescriptor {

private int fd;

private long handle;

/**

* Constructs an (invalid) FileDescriptor

* object.

*/

public /**/ FileDescriptor() {

fd = -1;

handle = -1;

}

private /* */ FileDescriptor(int fd) {

this.fd = fd;

handle = -1;

}

static {

initIDs();

}

/**

* A handle to the standard input stream. Usually, this file

* descriptor is not used directly, but rather via the input stream

* known as System.in .

*

* @see     java.lang.System#in

*/

public static final FileDescriptor in = standardStream(0);

/**

* A handle to the standard output stream. Usually, this file

* descriptor is not used directly, but rather via the output stream

* known as System.out .

* @see     java.lang.System#out

*/

public static final FileDescriptor out = standardStream(1);

/**

* A handle to the standard error stream. Usually, this file

* descriptor is not used directly, but rather via the output stream

* known as System.err .

*

* @see     java.lang.System#err

*/

public static final FileDescriptor err = standardStream(2);







请到「今天看啥」查看全文