zoukankan      html  css  js  c++  java
  • javaIO操作之字节输入流--InputStream

    /**
     *<li> InputStream类中定义的方法:
     *    <li>读取的数据保存在字节数组中,返回读取的字节数组的长度:public int read(byte[] b) throws IOException ;
     *    <li>读取部分数据保存在字节数组中,返回读取数据的长度:public int read(byte[] b,int off,int len)throws IOException ;
     *            如果文件内容读取到结尾字返回-1;
     */        
    package com.java.demo;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    public class TestDemo {
        public static void main(String args[]) throws Exception{
            //设置文件路径
            File fl = new File("e:"+File.separator+"hello" + File.separator+"demo" +File.separator+"java.txt" );
            if(fl.exists()){ //文件存在
                InputStream in = new FileInputStream(fl) ;
                byte data[] = new byte[1];
                int len = in.read(data) ;//将读取的内容保存在字节数组中,并且返回字节长度
                System.out.println("【"+new String(data,0,len) +"】");
            }
            
        }  
    }

    重要的实现方式:public abstract int read() throws IOException ;

    /**
     *<li>读取单个字节,如果读取到最后则返回-1: public abstract int read()throws IOException ;
     */        
    package com.java.demo;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    public class TestDemo {
        public static void main(String args[]) throws Exception{
            //设置文件路径
            File fl = new File("e:"+File.separator+"hello" + File.separator+"demo" +File.separator+"java.txt" );
            if(fl.exists()){ //文件存在
                InputStream in = new FileInputStream(fl) ;
                byte data[] = new byte[1024];
                int foot = 0 ;
                int temp = 0 ;
                while((temp = in.read()) != -1){ //说明存在数据
                    data[foot ++] = (byte)temp;//将读取的数据保存在字节数组中
                }
                in.close();
                System.out.println("[" + new String(data,0,foot)+"]");
            }
            
        }  
    }
  • 相关阅读:
    自己回答自己的问题
    作业5 四则运算 测试与封装 5.1 5.2
    2015430 加法阶段一的封装测试
    20150423 提问2
    Java 泛型中的<? super T>和<? extends T>
    ssh 查看端口占用
    Java 回调
    SpringMVC4+MyBaits3配置
    Selenium 远程执行和监听类
    Intellij idea主题
  • 原文地址:https://www.cnblogs.com/hu1056043921/p/7384179.html
Copyright © 2011-2022 走看看