java.io包 包含许多的 class ,程序可以使用这些类来读取和写入数据。 大部分类都实现了顺序访问流,顺序访问流可以分为2类

  • 读写字节的流
  • 读写Unicode字符的流

每个流都有他的特殊性,例如从文件读取或写入文件,在读取和写入的过程中过滤数据,或者是序列化对象

Java IO 类库

Java IO(1) - 图1刚接触IO的时候这个类库还是相对庞大的,且不明白各个 Class 的用法,更别谈他们之间的组合用法了

从字面上看Java IO分为2块,分别是:

  • 字节流,网络传输都是使用的字节流,所以需要直接支持的
  • 字符流,日常使用字节流其实是不方便的,例如一个图片,一个文件所以Java提供了字符流来进行操作.

输入输出分别是

  • 输入,代表流的InputStream,代表字符的Reader
  • 输出,代表流的OutputStream,代表字符的Writer

实例

字节流

  1. public static void main(String[] args) throws IOException {
  2. final String path = "/paths/Test.java";
  3. {
  4. //单字节读取
  5. try (InputStream inputStream = new FileInputStream(path)) {
  6. int read;
  7. while ((read = inputStream.read()) != -1) {
  8. System.out.print(new String(new byte[]{(byte) read}, 0, 1));
  9. }
  10. }
  11. }
  12. {
  13. //多字节夺取
  14. try (InputStream inputStream = new FileInputStream(path)) {
  15. byte[] bytes = new byte[1024];
  16. int read;
  17. while ((read = inputStream.read(bytes)) != -1) {
  18. System.out.print(new String(bytes, 0, read));
  19. }
  20. }
  21. }
  22. {
  23. //整个文件读取
  24. try (InputStream inputStream = new FileInputStream(path)) {
  25. final int available = inputStream.available();
  26. byte[] bytes = new byte[available];
  27. inputStream.read(bytes, 0, bytes.length);
  28. System.out.println(new String(bytes, StandardCharsets.UTF_8));
  29. }
  30. }
  31. }

单个字节读取肯定不方便,多个字节读取也有问题

  • 一个ASCII字符是1个字节,而汉字是UTF-8编码,是不确定有多少个字节的,如果一个一个字节的读取必然出现乱码,多字节夺取如果刚好读取到这部分也会形成乱码

整个文件读取肯定也不现实,如果一个文件是10G,机器只有4G的内存. :(

针对整个问题,我能不能使用读字符的形式来读取本地文件.

字符读

  1. try (InputStream inputStream = new FileInputStream(path)) {
  2. final InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
  3. int read;
  4. while ((read = inputStreamReader.read()) != -1) {
  5. System.out.print(new String(new char[]{(char) read}));
  6. }
  7. }

一次读取一个字符,从结果来看直接消灭了乱码 使用方式就是在inputStream的形式上进行了一次wrapper,读取字节的过程中将其转换成字符

那么还能不能更方便一点呢,例如一次读取一行.

  1. try (InputStream inputStream = new FileInputStream(path);
  2. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
  3. String line;
  4. while ((line = bufferedReader.readLine()) != null) {
  5. System.out.println(line);
  6. }
  7. }

在上述单个字符的情况下又进行了一次包装,一直读取直到读完一行.

各种各种的进化以及组合形式的出现都是为了让我们更加方便的进行读写操作. 读如此,写也是如此..(评论区)

背后是什么

我们简简单单的一个 writeread 就能写入文件和读取文件了,那么背后究竟是怎么一回事呢.

为了了解这个,我们先看一个c是怎么读写文件的 :)

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <fcntl.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. int main(void)
  7. {
  8. int in;
  9. char buffer[1024];
  10. char tempWrite[10] = "test write";
  11. //系统调用open打开in.txt 文件(读写,如果没有就创建文件)
  12. //in 文件描述福
  13. in = open("in.txt", O_RDWR | O_CREAT);
  14. if (-1 == in) // 打开文件失败,则异常返回
  15. {
  16. return -1;
  17. }
  18. //系统调用写入文件
  19. write(in, tempWrite, 10);
  20. //系统调用关闭文件描述符
  21. close(in);
  22. return 0;
  23. }
  24. //gcc -o read readAndWrite.c && ./read

分别是 open文件, 准备写入的数据write写入文件close关闭文件

打开文件

  1. public FileInputStream(File file) throws FileNotFoundException {
  2. String name = (file != null ? file.getPath() : null);
  3. SecurityManager security = System.getSecurityManager();
  4. if (security != null) security.checkRead(name);
  5. if (name == null) { throw new NullPointerException();
  6. if (file.isInvalid()) throw new FileNotFoundException("Invalid file path");
  7. fd = new FileDescriptor();
  8. fd.attach(this);
  9. path = name;
  10. open(name);
  11. }
  12. // wrap native call to allow instrumentation
  13. /**
  14. * Opens the specified file for reading.
  15. * @param name the name of the file
  16. */
  17. private void open(String name) throws FileNotFoundException {
  18. open0(name);
  19. }
  20. private native void open0(String name) throws FileNotFoundException;
  • 基本的文件检查
  • 创建 文件描述符FD
  • 调用native方法 open0

    grep -nr “搜索的字符串” . (grep -nr “Java_java_io_FileInputStream_open0” .)

  1. jdk8u_jdk/src/share/native/java/io/FileInputStream.c +60
  2. JNIEXPORT void JNICALL
  3. Java_java_io_FileInputStream_open0(JNIEnv *env, jobject this, jstring path) {
  4. fileOpen(env, this, path, fis_fd, O_RDONLY);
  5. }
  6. ------------------------------------------------------------------------------
  7. vim +101 ./jdk8u_jdk/src/solaris/native/java/io/io_util_md.c
  8. void fileOpen(JNIEnv *env, jobject this, jstring path, jfieldID fid, int flags)
  9. {
  10. //WITH_PLATFORM_STRING 执行{}之间的代码
  11. WITH_PLATFORM_STRING(env, path, ps) {
  12. FD fd;
  13. //....省略部分不重要的
  14. fd = handleOpen(ps, flags, 0666);
  15. if (fd != -1) {
  16. SET_FD(this, fd, fid);
  17. } else {
  18. throwFileNotFoundException(env, path);
  19. }
  20. } END_PLATFORM_STRING(env, ps);
  21. }
  22. ------------------------------------------------------------------------------
  23. vim +79 ./jdk8u_jdk/src/solaris/native/java/io/io_util_md.c
  24. FD handleOpen(const char *path, int oflag, int mode) {
  25. FD fd;
  26. //RESTARTABLE 执行到成功为止
  27. //The open64() function is a part of the large file extensions, and is //equivalent to calling open() with the O_LARGEFILE flag.
  28. //调用open64打开文件,== open() + O_LARGEFILE
  29. RESTARTABLE(open64(path, oflag, mode), fd);
  30. if (fd != -1) {
  31. struct stat64 buf64;
  32. int result;
  33. RESTARTABLE(fstat64(fd, &buf64), result);
  34. if (result != -1) {
  35. if (S_ISDIR(buf64.st_mode)) {
  36. close(fd);
  37. errno = EISDIR;
  38. fd = -1;
  39. }
  40. } else {
  41. close(fd);
  42. fd = -1;
  43. }
  44. }
  45. return fd;
  46. }
  47. ------------------------------------------------------------------------------

RESTARTABLE
  1. /*
  2. * vim +95 ./solaris/native/java/io/io_util_md.h
  3. * Retry the operation if it is interrupted
  4. */
  5. #define RESTARTABLE(_cmd, _result) do { \
  6. do { \
  7. _result = _cmd; \
  8. } while((_result == -1) && (errno == EINTR)); \
  9. } while(0)

读取数据

  1. inputStream.read(); 读取单个字节
  2. -------------------------------------------------------------------------------
  3. vim +64 jdk8u_jdk/src/share/native/java/io/FileInputStream.c
  4. JNIEXPORT jint JNICALL
  5. Java_java_io_FileInputStream_read0(JNIEnv *env, jobject this) {
  6. return readSingle(env, this, fis_fd);
  7. }
  8. jint
  9. readSingle(JNIEnv *env, jobject this, jfieldID fid) {
  10. jint nread;
  11. char ret;
  12. //获取文件描述符
  13. FD fd = GET_FD(this, fid);
  14. if (fd == -1) {
  15. JNU_ThrowIOException(env, "Stream Closed");
  16. return -1;
  17. }
  18. nread = IO_Read(fd, &ret, 1);
  19. if (nread == 0) { /* EOF */
  20. return -1;
  21. } else if (nread == -1) { /* error */
  22. JNU_ThrowIOExceptionWithLastError(env, "Read error");
  23. }
  24. return ret & 0xFF;
  25. }
  26. #define IO_Read handleRead
  27. vim +157 ./solaris/native/java/io/io_util_md.c
  28. ssize_t
  29. handleRead(FD fd, void *buf, jint len)
  30. {
  31. ssize_t result;
  32. RESTARTABLE(read(fd, buf, len), result);
  33. return result;
  34. }
  35. 成功通过系统调用读取到一个字节 read(fd, buf, len)
  36. -------------------------------------------------------------------------------
  37. byte[] b = new byte[1024]; //读取到字节数组中
  38. inputStream.readBytes(b, 0, b.length); 读取1024子字节到数组b
  39. private native int readBytes(byte b[], int off, int len) throws IOException;
  40. vim +74 ./share/native/java/io/io_util.c
  41. jint readBytes(JNIEnv *env, jobject this, jbyteArray bytes,
  42. jint off, jint len, jfieldID fid)
  43. {
  44. jint nread;
  45. char stackBuf[BUF_SIZE];//BUF_SIZE == 8192
  46. char *buf = NULL;
  47. FD fd;
  48. if (IS_NULL(bytes)) {
  49. JNU_ThrowNullPointerException(env, NULL);
  50. return -1;
  51. }
  52. if (outOfBounds(env, off, len, bytes)) {
  53. JNU_ThrowByName(env, "java/lang/IndexOutOfBoundsException", NULL);
  54. return -1;
  55. }
  56. if (len == 0) {
  57. return 0;
  58. } else if (len > BUF_SIZE) {
  59. //如果超过8M,那么需要重新申请内存
  60. buf = malloc(len);
  61. if (buf == NULL) {// OOM
  62. JNU_ThrowOutOfMemoryError(env, NULL);
  63. return 0;
  64. }
  65. } else {
  66. buf = stackBuf;
  67. }
  68. fd = GET_FD(this, fid);
  69. if (fd == -1) {
  70. JNU_ThrowIOException(env, "Stream Closed");
  71. nread = -1;
  72. } else {
  73. nread = IO_Read(fd, buf, len);
  74. if (nread > 0) {
  75. (*env)->SetByteArrayRegion(env, bytes, off, nread, (jbyte *)buf);
  76. } else if (nread == -1) {
  77. JNU_ThrowIOExceptionWithLastError(env, "Read error");
  78. } else { /* EOF */
  79. nread = -1;
  80. }
  81. }
  82. if (buf != stackBuf) {
  83. // 释放内存
  84. free(buf);
  85. }
  86. return nread;
  87. }
  88. Note: 如果一次读取超过8M需要重新申请内存. 所以.....
  89. IO_Read 同上,还是一样的系统调用

整体上的读取还是和c差不多,添加了一些额外的检查和JNI的调用,但是原则上的流程还是和C一致的.

关闭文件

  1. void
  2. fileClose(JNIEnv *env, jobject this, jfieldID fid)
  3. {
  4. FD fd = GET_FD(this, fid);
  5. if (fd == -1) {
  6. return;
  7. }
  8. /* Set the fd to -1 before closing it so that the timing window
  9. * of other threads using the wrong fd (closed but recycled fd,
  10. * that gets re-opened with some other filename) is reduced.
  11. * Practically the chance of its occurance is low, however, we are
  12. * taking extra precaution over here.
  13. */
  14. SET_FD(this, -1, fid);
  15. //...一部分判断挪走
  16. if (close(fd) == -1) {
  17. JNU_ThrowIOExceptionWithLastError(env, "close failed");
  18. }
  19. }

关于Java的文件描述符可以看看这篇文章

总结

  • java.io 类库比较杂,使用方式主要和 Buffered 组合使用,初次接触可能会觉得比较麻烦,多次使用形成肌肉记忆以后则简单需要了
  • Java的文件io流程上和C调用差不多,大体都是 open read write close
    • 相比于直接使用系统调用,Java的读取文件会多一次拷贝!因为使用read读取文件内容到C空间的数组后,需要拷贝数据到JVM的堆空间的数组中

参考链接