IO流(2)

 判断使用输入流还是输出流:以当前程序为参数照物,观察数据是流入还是流出,如果流出则使用输出流,如果数据是流入,则使用输入流

如果是按照数据的流向划分:

  • 输入流
  • 输出流

如果按照处理的单位划分:

  • 字节流: 字节流读取得都是文件中二进制数据,读取到二进制数据不会经过任何的处理。
  • 字符流: 字符流读取的数据是以字符为单位的 。 字符流也是读取文件中的二进制数据,不过会把这些二进制数据转换成我们能 识别的字符。
    • 字符流 = 字节流 + 解码

输入字节流:
--------| InputStream 所有输入字节流的基类 抽象类
------------| FileInputStream 读取文件数据的输入字节流
使用FileInputStream读取文件数据的步骤:

  1. 找到目标文件
  2. 建立数据的输入通道。
  3. 读取文件中的数据。
  4. 关闭 资源.
public class Demo3 {
    public static void main(String[] args) throws IOException {
        readText();
//        readText2();
        readText3();
        readText4();
    }
//    使用缓冲数组读取-效率最高
    public static void readText4() throws IOException {
        long startTime = System.currentTimeMillis();
        File file=new File("F:\a.txt");
//        建立数据通道
        FileInputStream fileInputStream = new FileInputStream(file);
        //建立缓冲数组配合循环读取文件的数据。
        int length = 0; //保存每次读取到的字节个数。
        byte[] buf = new byte[1024]; //存储读取到的数据    缓冲数组 的长度一般是1024的倍数,因为与计算机的处理单位。  理论上缓冲数组越大,效率越高
//        byte[] buf = new byte[1024*3];
        while((length = fileInputStream.read(buf))!=-1){ // read方法如果读取到了文件的末尾,那么会返回-1表示。
            System.out.print(new String(buf,0,length));
        }
        long endTime=System.currentTimeMillis();
        //关闭资源
        fileInputStream.close();
        System.out.println("处理 的时间"+(startTime-endTime));
    }
//    效率太低,使用循环读取文件的数据
    public static void readText3() throws IOException {
//        建立目录
        File file=new File("F:\a.txt");
//        建立数据通道
        FileInputStream fileInputStream = new FileInputStream(file);
        int content=0;
        while((content=fileInputStream.read())!=-1){
            System.out.println((char)content);
        }
        fileInputStream.close();
    }
    public static void readText2() throws IOException {
//        建立目录
        File file=new File("F:\a.txt");
//        建立数据通道
        FileInputStream fileInputStream = new FileInputStream(file);
        String str="";
        for(int i=0;i<file.length();i++){
            str=str+(char)fileInputStream.read();
        }
        System.out.println(str);
    }
//    无法读取一个完整的文件数据
    public static void readText() throws IOException {
//        建立目录
        File file=new File("F:\a.txt");
//        建立数据通道
        FileInputStream fileInputStream = new FileInputStream(file);
//        读取文件中的数据
        try {
            int content=fileInputStream.read();
            System.out.println("读取到的数据"+(char)content);
            fileInputStream.close();//释放资料
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容

4、随机读取文件内容 

public class ReadFromFile {
    /**
     * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
     */
    public static void readFileByBytes(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容,一次读一个字节:");
            // 一次读一个字节
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.write(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        try {
            System.out.println("以字节为单位读取文件内容,一次读多个字节:");
            // 一次读多个字节
            byte[] tempbytes = new byte[100];
            int byteread = 0;
            in = new FileInputStream(fileName);
            ReadFromFile.showAvailableBytes(in);
            // 读入多个字节到字节数组中,byteread为一次读入的字节数
            while ((byteread = in.read(tempbytes)) != -1) {
                System.out.write(tempbytes, 0, byteread);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 以字符为单位读取文件,常用于读文本,数字等类型的文件
     */
    public static void readFileByChars(String fileName) {
        File file = new File(fileName);
        Reader reader = null;
        try {
            System.out.println("以字符为单位读取文件内容,一次读一个字节:");
            // 一次读一个字符
            reader = new InputStreamReader(new FileInputStream(file));
            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                // 对于windows下,
这两个字符在一起时,表示一个换行。
                // 但如果这两个字符分开显示时,会换两次行。
                // 因此,屏蔽掉
,或者屏蔽
。否则,将会多出很多空行。
                if (((char) tempchar) != '
') {
                    System.out.print((char) tempchar);
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println("以字符为单位读取文件内容,一次读多个字节:");
            // 一次读多个字符
            char[] tempchars = new char[30];
            int charread = 0;
            reader = new InputStreamReader(new FileInputStream(fileName));
            // 读入多个字符到字符数组中,charread为一次读取字符数
            while ((charread = reader.read(tempchars)) != -1) {
                // 同样屏蔽掉
不显示
                if ((charread == tempchars.length)
                        && (tempchars[tempchars.length - 1] != '
')) {
                    System.out.print(tempchars);
                } else {
                    for (int i = 0; i < charread; i++) {
                        if (tempchars[i] == '
') {
                            continue;
                        } else {
                            System.out.print(tempchars[i]);
                        }
                    }
                }
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 以行为单位读取文件,常用于读面向行的格式化文件
     */
    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容,一次读一整行:");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println("line " + line + ": " + tempString);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 随机读取文件内容
     */
    public static void readFileByRandomAccess(String fileName) {
        RandomAccessFile randomFile = null;
        try {
            System.out.println("随机读取一段文件内容:");
            // 打开一个随机访问文件流,按只读方式
            randomFile = new RandomAccessFile(fileName, "r");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            // 读文件的起始位置
            int beginIndex = (fileLength > 4) ? 4 : 0;
            // 将读文件的开始位置移到beginIndex位置。
            randomFile.seek(beginIndex);
            byte[] bytes = new byte[10];
            int byteread = 0;
            // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
            // 将一次读取的字节数赋给byteread
            while ((byteread = randomFile.read(bytes)) != -1) {
                System.out.write(bytes, 0, byteread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 显示输入流中还剩的字节数
     */
    private static void showAvailableBytes(InputStream in) {
        try {
            System.out.println("当前字节输入流中的字节数为:" + in.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String fileName = "C:/temp/newTemp.txt";
        ReadFromFile.readFileByBytes(fileName);
        ReadFromFile.readFileByChars(fileName);
        ReadFromFile.readFileByLines(fileName);
        ReadFromFile.readFileByRandomAccess(fileName);
    }
}
原文地址:https://www.cnblogs.com/chenzxl/p/7868595.html