JDK源码阅读-FileOutputStream
导语
FileOutputStream
用户打开文件并获取输出流。
打开文件
public FileOutputStream(File file, boolean append)
throws FileNotFoundException
{
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(name);
}
if (name == null) {
throw new NullPointerException();
}
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
}
this.fd = new FileDescriptor();
fd.attach(this);
this.append = append; // 记录是否是append追加模式
this.path = name;
open(name, append);
}
private void open(String name, boolean append)
throws FileNotFoundException {
open0(name, append);
}
private native void open0(String name, boolean append)
throws FileNotFoundException;
// jdk/src/solaris/native/java/io/FileOutputStream_md.c
JNIEXPORT void JNICALL
Java_java_io_FileOutputStream_open(JNIEnv *env, jobject this,
jstring path, jboolean append) {
// 使用O_WRONLY,O_CREAT模式打开文件,如果文件不存在会新建文件
// 如果java中指定append参数为true,则使用O_APPEND追加模式
// 如果java中指定append参数为false,则使用O_TRUNC模式,如果文件存在内容,会清空掉
fileOpen(env, this, path, fos_fd,
O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC));
}
fileOpen
之后的流程与FileInputStream
的一致,可以参考JDK源码阅读-FileInputStream
写文件
FileOutputStream
提供了三个write函数:
public void write(int b) throws IOException {
write(b, append);
}
public void write(byte b[]) throws IOException {
writeBytes(b, 0, b.length, append);
}
public void write(byte b[], int off, int len) throws IOException {
writeBytes(b, off, len, append);
}
private native void write(int b, boolean append) throws IOException;
private native void writeBytes(byte b[], int off, int len, boolean append)
throws IOException;
// jdk/src/solaris/native/java/io/FileOutputStream_md.c
JNIEXPORT void JNICALL
Java_java_io_FileOutputStream_write(JNIEnv *env, jobject this, jint byte, jboolean append) {
writeSingle(env, this, byte, append, fos_fd);
}
JNIEXPORT void JNICALL
Java_java_io_FileOutputStream_writeBytes(JNIEnv *env,
jobject this, jbyteArray bytes, jint off, jint len, jboolean append) {
writeBytes(env, this, bytes, off, len, append, fos_fd);
}
// jdk/src/share/native/java/io/io_util.c
void
writeSingle(JNIEnv *env, jobject this, jint byte, jboolean append, jfieldID fid) {
// Discard the 24 high-order bits of byte. See OutputStream#write(int)
char c = (char) byte;
jint n;
// 获取记录在FileDescriptor中的文件描述符
FD fd = GET_FD(this, fid);
if (fd == -1) {
JNU_ThrowIOException(env, "Stream Closed");
return;
}
// 追加模式和普通模式使用不同的函数
if (append == JNI_TRUE) {
n = IO_Append(fd, &c, 1);
} else {
n = IO_Write(fd, &c, 1);
}
if (n == -1) {
JNU_ThrowIOExceptionWithLastError(env, "Write error");
}
}
void
writeBytes(JNIEnv *env, jobject this, jbyteArray bytes,
jint off, jint len, jboolean append, jfieldID fid)
{
jint n;
char stackBuf[BUF_SIZE];
char *buf = NULL;
FD fd;
// 判断Java传入的byte数组是否是null
if (IS_NULL(bytes)) {
JNU_ThrowNullPointerException(env, NULL);
return;
}
// 判断off和len参数是否数组越界
if (outOfBounds(env, off, len, bytes)) {
JNU_ThrowByName(env, "java/lang/IndexOutOfBoundsException", NULL);
return;
}
// 如果写入长度为0,直接返回0
if (len == 0) {
return;
} else if (len > BUF_SIZE) {
// 如果写入长度大于BUF_SIZE(8192),无法使用栈空间buffer
// 需要调用malloc在堆空间申请buffer
buf = malloc(len);
if (buf == NULL) {
JNU_ThrowOutOfMemoryError(env, NULL);
return;
}
} else {
buf = stackBuf;
}
// 复制Java传入的byte数组数据到C空间的buffer中
(*env)->GetByteArrayRegion(env, bytes, off, len, (jbyte *)buf);
if (!(*env)->ExceptionOccurred(env)) {
off = 0;
while (len > 0) {
// 获取记录在FileDescriptor中的文件描述符
fd = GET_FD(this, fid);
if (fd == -1) {
JNU_ThrowIOException(env, "Stream Closed");
break;
}
// 追加模式和普通模式使用不同的函数
if (append == JNI_TRUE) {
n = IO_Append(fd, buf+off, len);
} else {
n = IO_Write(fd, buf+off, len);
}
if (n == -1) {
JNU_ThrowIOExceptionWithLastError(env, "Write error");
break;
}
off += n;
len -= n;
}
}
if (buf != stackBuf) {
free(buf);
}
}
IO_Write
/IO_Append
虽然看起来是两个不同的函数,其实是两个不同的宏定义,指向同一个函数handleWrite
:
// jdk/src/solaris/native/java/io/io_util_md.h
#define IO_Write handleWrite
#define IO_Append handleWrite
handleWrite
中调用write
系统调用写入数据:
// jdk/src/solaris/native/java/io/io_util_md.c
ssize_t
handleWrite(FD fd, const void *buf, jint len)
{
ssize_t result;
RESTARTABLE(write(fd, buf, len), result);
return result;
}
FileOutputStream#write(byte[], int, int)
的主要流程:
- 检查参数是否合法(byte数组不能为空,off和len没有越界)
- 判断读取的长度,如果等于0直接返回0,如果大于BUF_SIZE需要在堆空间申请内存,如果`0则直接在使用栈空间的缓存
- 从Java空间的byte数组复制数据到中C空间的char数组中
- 调用
write
系统调用写文件内容到系统中
重要收获:
- 使用
FileOutputStream#write(byte[], int, int)
写入的长度,len一定不能大于8192!因为在小于8192时,会直接利用栈空间的char数组,如果大于,则需要调用malloc申请内存,并且还需要free释放内存,这是非常消耗时间的。 - 相比于直接使用系统调用,Java的写入会多一次拷贝!
关闭文件
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
if (channel != null) {
channel.close();
}
fd.closeAll(new Closeable() {
public void close() throws IOException {
close0();
}
});
}
FileOutputStream
关闭文件的逻辑和FileInputStream
关闭文件的逻辑是一样的,参考JDK源码阅读-FileDescriptor
总结
FileOutputStream
打开文件使用open
系统调用FileOutputStream
写入文件使用write
系统调用FileOutputStream
关闭文件使用close
系统调用- 使用
FileOutputStream#write(byte[], int, int)
写入的长度,len一定不能大于8192!因为在小于8192时,会直接利用栈空间的char数组,如果大于,则需要调用malloc申请内存,并且还需要free释放内存,这是非常消耗时间的。 - 相比于直接使用系统调用,Java的写入会多一次拷贝!
FileOutputStream#write
是无缓冲的,所以每次调用对对应一次系统调用,可能会有较低的性能,需要结合BufferedOutputStream
提高性能
JDK源码阅读-FileOutputStream的更多相关文章
- JDK源码阅读-RandomAccessFile
本文转载自JDK源码阅读-RandomAccessFile 导语 FileInputStream只能用于读取文件,FileOutputStream只能用于写入文件,而对于同时读取文件,并且需要随意移动 ...
- JDK源码阅读-FileInputStream
本文转载自JDK源码阅读-FileInputStream 导语 FileIntputStream用于打开一个文件并获取输入流. 打开文件 我们来看看FileIntputStream打开文件时,做了什么 ...
- JDK源码阅读-FileDescriptor
本文转载自JDK源码阅读-FileDescriptor 导语 操作系统使用文件描述符来指代一个打开的文件,对文件的读写操作,都需要文件描述符作为参数.Java虽然在设计上使用了抽象程度更高的流来作为文 ...
- JDK源码阅读(三):ArraryList源码解析
今天来看一下ArrayList的源码 目录 介绍 继承结构 属性 构造方法 add方法 remove方法 修改方法 获取元素 size()方法 isEmpty方法 clear方法 循环数组 1.介绍 ...
- JDK源码阅读(一):Object源码分析
最近经过某大佬的建议准备阅读一下JDK的源码来提升一下自己 所以开始写JDK源码分析的文章 阅读JDK版本为1.8 目录 Object结构图 构造器 equals 方法 getClass 方法 has ...
- 利用IDEA搭建JDK源码阅读环境
利用IDEA搭建JDK源码阅读环境 首先新建一个java基础项目 基础目录 source 源码 test 测试源码和入口 准备JDK源码 下图框起来的路径就是jdk的储存位置 打开jdk目录,找到sr ...
- JDK源码阅读-ByteBuffer
本文转载自JDK源码阅读-ByteBuffer 导语 Buffer是Java NIO中对于缓冲区的封装.在Java BIO中,所有的读写API,都是直接使用byte数组作为缓冲区的,简单直接.但是在J ...
- JDK源码阅读-Reference
本文转载自JDK源码阅读-Reference 导语 Java最初只有普通的强引用,只有对象存在引用,则对象就不会被回收,即使内存不足,也是如此,JVM会爆出OOME,也不会去回收存在引用的对象. 如果 ...
- JDK源码阅读-DirectByteBuffer
本文转载自JDK源码阅读-DirectByteBuffer 导语 在文章JDK源码阅读-ByteBuffer中,我们学习了ByteBuffer的设计.但是他是一个抽象类,真正的实现分为两类:HeapB ...
随机推荐
- 函数式编程(json、pickle、shelve)
本节内容 前言 json模块 pickle模块 shelve模块 总结 一.前言 1. 现实需求 每种编程语言都有各自的数据类型,其中面向对象的编程语言还允许开发者自定义数据类型(如:自定义类),Py ...
- ubuntu下scala下载+集成IDEA开发环境
环境须知: ubuntu 16.04 scala 2.11.0 jdk 1.8.0 Idea 2016.3 JDK环境安装 (1)安装jdk, 注意scala很好的支持jdk 1.8 的jvm 编译环 ...
- Java安全之jar包调试技巧
Java安全之jar包调试技巧 调试程序 首先还是创建一个工程,将jar包导入进来 调试模式的参数 启动中需要加入特定参数才能使用debug模式,并且需要开放调试端口 JDK5-8: -agentli ...
- Codeforces Round #594 (Div. 2) D1 - The World Is Just a Programming Task (贪心)
思路:枚举换的位置i,j 然后我们要先判断改序列能否完全匹配 如果可以 那我们就需要把差值最大的位置换过来 然后直接判断就行
- Java的awt包的使用实例和Java的一些提示框
一.awt的一些组件 Label l1=new Label("姓名:"); //标签 Label l2=new Label("密码:"); TextField ...
- hdu3652B-number (数位dp)
Problem Description A wqb-number, or B-number for short, is a non-negative integer whose decimal for ...
- hdu5627 Clarke and MST (并查集)
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Total Submission ...
- AcWing 247. 亚特兰蒂斯 (线段树,扫描线,离散化)
题意:给你\(n\)个矩形,求矩形并的面积. 题解:我们建立坐标轴,然后可以对矩形的横坐标进行排序,之后可以遍历这些横坐标,这个过程可以想像成是一条线从左往右扫过x坐标轴,假如这条线是第一次扫过矩形的 ...
- Codeforces Gym-102219 2019 ICPC Malaysia National E. Optimal Slots(01背包+输出路径)
题意:给你一个体积为\(T\)的背包,有\(n\)个物品,每个物品的价值和体积都是是\(a_{i}\),求放哪几个物品使得总价值最大,输出它们,并且输出价值的最大值. 题解:其实就是一个01背包输出路 ...
- Linux 搭建网站
wget http://dl.wdlinux.cn/lanmp_laster.tar.gz tar zxvf lanmp_laster.tar.gz sh lanmp.sh https://www.w ...