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("关闭文件输入流失败");
                    }
                }
            }
        }
    }
  • 相关阅读:
    BZOJ 2456: mode
    替罪羊树(模板)
    LUOGU P4168 [Violet]蒲公英
    洛谷题目统计爬虫
    LUOGU P3819 松江1843路
    bzoj 2946 [Poi2000]公共串——后缀自动机
    bzoj 4032 [HEOI2015]最短不公共子串——后缀自动机
    bzoj 2555 SubString——后缀自动机+LCT
    洛谷 3804 【模板】后缀自动机
    洛谷 4106 / bzoj 3614 [HEOI2014]逻辑翻译——思路+类似FWT
  • 原文地址:https://www.cnblogs.com/jiaoqiang/p/8378379.html
Copyright © 2011-2022 走看看