1

我试图弄清楚java如何将字节写入磁盘。

如果我查看 Randomaccesfile 实现,它已经声明了一个本地方法,并在调用 write(byte[]) 时调用所述本地方法写入磁盘。

randomaccesfile 的源代码:http: //grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/java/io/RandomAccessFile.java#RandomAccessFile.writeBytes%28byte%5B%5D %2Cint%2Cint%29

private native void writeBytes(byte b[], int off, int len) throws IOException;

public void write(byte b[]) throws IOException {
    writeBytes(b, 0, b.length);
}

我在 OpenJDK 内部搜索了 writeBytes,并在io_util.c Here the functions IO_Append(fd, buf+off, len);and IO_Write(fd, buf+off, len); are called 中找到了它。

这些函数可以在 io_util_md.h 中的 JDK 中找到适用于 Windows 和 Solaris

/*
* Route the routines
*/
#define IO_Sync fsync
#define IO_Read handleRead
#define IO_Write handleWrite
#define IO_Append handleWrite
#define IO_Available handleAvailable
#define IO_SetLength handleSetLength

为什么我不能为 Linux 找到相同的东西?做什么io_appendio_write实际做什么?我找不到它们是如何实现的。

4

1 回答 1

2

似乎 Solaris 和 Linux 共享以下所有内容的本机代码库 http://hg.openjdk.java.net/jdk7/jdk7/jdk/

io_util_md.h定义(用于 Solaris 和 Linux)

#define IO_Append JVM_Write
#define IO_Write JVM_Write 

现在JVM_Write在热点代码库中定义,在jvm.cpp中:

JVM_LEAF(jint, JVM_Write(jint fd, char *buf, jint nbytes))
    JVMWrapper2("JVM_Write (0x%x)", fd);
    //%note jvm_r6
    return (jint)os::write(fd, buf, nbytes);
JVM_END

调用依赖于操作系统的写入函数。Linux 实现在os_linux.inline.hpp

inline size_t os::write(int fd, const void *buf, unsigned int nBytes) {
    size_t res;
    RESTARTABLE((size_t) ::write(fd, buf, (size_t) nBytes), res);
    return res;
}
于 2015-10-03T19:05:53.253 回答