InputStream类

A类,使用其 实例化的子类

public class InputStreamDemo {
    
//  构造方法:为流对象绑定数据源
    public static void main(String[] argStrings) {
            
            /*内部方法 有返回值
             * int read(int b)
             * int read(byte[] b)
             * int read(byte[] b,int start,int end)
             */
            
            FileInputStreamDemo.func();
            FileInputStreamDemo.func2();
        }
    
    static class FileInputStreamDemo{
        public static void func() {
            FileInputStream fileInputStream=null;
            try {
                fileInputStream = new FileInputStream("e:\\fileOut.txt");
//              重点:read()执行一次,自动读取下一个字节
//              返回值返回的是读取到的字节
//              到达文件结尾,返回-1
                
//              循环读取
                int len=0;
                while ((len=fileInputStream.read())!=-1) {
                    System.out.println(len);
                }
                
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (fileInputStream!=null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
        public static void func2() {
//          读取字节数组
            FileInputStream fileInputStream=null;
            try {
                fileInputStream = new FileInputStream("e:\\fileOut.txt");           
                byte[] bytes=new byte[1024];
//              重点:返回有效字节数
                int len=0;
                while ((len=fileInputStream.read(bytes))!=-1) {
//                  重点:使用String类构造重载 将字节数组转换字符串 同时设定转换的数组长度
                    String string=new String(bytes,0,len);
                    System.out.println(string);
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (fileInputStream!=null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容