InputStream简单源码分析

package com.test;

import java.io.*;
import java.util.Arrays;

public class FileReadAndWrite {
        public static void readFile(String path){
        try {
            FileInputStream is = new FileInputStream(path);//使用这个输出的是一个个数字,
            int read = is.read();
            while (read!=-1){//这里为什么是-1,是源码里的规定的
                System.out.print(read);
                read = is.read();
            }
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args){
        String path = "F:/a.txt";
        readFile(path);
    }
}
下面列出对应的read部分的源码

public int read() throws IOException {
    Object traceContext = IoTrace.fileReadBegin(path);
    int b = 0;
    try {
        b = read0();//这个方法会在下面列出
    } finally {
        IoTrace.fileReadEnd(traceContext, b == -1 ? 0 : 1);//这里就是规定的地方
    }
    return b;
}
 
  
private native int read0() throws IOException;//这里有native修饰,native方法代表这是一个非java方法,他调用了别的语言写的
如果文件的内容是字符最终输出的结果为一串数字,这些数字是其Ascall

当文件的内容为汉字时,输出的是186195


你可能感兴趣的:(java源码)