zoukankan      html  css  js  c++  java
  • 二、java IO--使用字节流读取文件

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    /**
        一、读取文件
        1、建立联系   File对象 源头
        2、选择流     文件输入流  InputStream FileInputStream
        3、操作  : byte[] car =new byte[1024];  +read+读取大小  --->输出
        4、释放资源 :关闭
     */
    public class ReadFile {
        public static void main(String[] args) {
            String string = "F:/read.txt";
            myRead(string);
        }
        /**
         * 读取文件
         * @param string
         */
        public static void myRead(String string){
            File file = new File(string);    //1、建立连接
            InputStream is = null;
            try {
                is = new FileInputStream(file);    //2、选择流(此处为输入流)
    //            //和上一句功能一样,BufferedInputStream是增强流,加上之后能提高输入效率,建议!
    //            is = new BufferedInputStream(new FileInputStream(file));
                int len = 0;
                byte[] car = new byte[1024];
                while((len = is.read(car))!= -1) {    //3、操作:以每次car大小读取
                    String ss = new String(car,0,len);    // 将byte类型的数组转化成字符串,方便下面输出
                    System.out.println(ss);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("文件不存在!");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("读取文件失败!");
            }finally {
                if (is != null) {    //若is还存在就需要释放,否则不需要释放
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("关闭文件输入流失败");
                    }
                }
            }
        }
    }
  • 相关阅读:
    python的进程与线程
    推荐一个GOLANG入门很好的网址
    为什么Python 3.6以后字典有序并且效率更高?
    git实用指南
    常用正则总结
    简单小结密码学入门知识点
    什么是k8s
    win10下apache superset的使用
    Maven工作记录
    JDK下载地址和安装
  • 原文地址:https://www.cnblogs.com/jiaoqiang/p/8378379.html
Copyright © 2011-2022 走看看