• 文件的输入流


    不管是字节流或者字符流,在java中他们使用的过程都很相似。对于一个输入流:

    1. 首先是创建一个与数据源相关的对象。如果数据源是硬盘上的文件,一个FileInputStream对象应当与此对应;
    2. 之后使用该对象的方法read()从哪个流中读取信息,即返回读取一个字节;
    3. 完成了从流中读取信息之后,调用close()方法关闭对流的使用。

    文件输入流可以使用构造方法FileInputStream(String)创建

    下面的语句创建了一个文件输入流:

    FileInputStream fis = new FileInputStream("scores.dat");

    下面的语句使用while循环来读取文件输入流对象df中的数据:

    复制代码
    int newBytes = 0;
    while (newBytes != -1)
    {
     newBytes = df.read();
    System.out.print(newBytes + " ");   
    }
    复制代码

    以字节方式读取源程序对应的类文件,并显示出来。

    复制代码
    //ReadBytes.java
    import java.io.*;
    public class ReadBytes {
    public static void main(String[] args) {
        try{//create file input stream file
            FileInputStream file = new FileInputStream("ReadBytes.class");
            boolean eof = false;
            int count = 0;
            while(!eof)//file not end 
            {
                int input = file.read();//read one character
                System.out.print(input + " ");//output the character
                if(input == -1)
                    eof = true;
                else    count++;
            }
            file.close();
            System.out.print("
     Bytes read:" + count);//output the count
        } catch(IOException e) {
            System.out.println("Error -- " + e.toString());
        }
    }
    }

    转载来自:http://www.cnblogs.com/gride-glory/p/7719075.html
  • 相关阅读:
    protobuf使用遇到的坑
    嵌入式开发入门心得记录
    vim编辑模式下黑色背景,下来过程中出现白条的问题
    linux中awk的应用
    ntp时间同步
    mysql5.5适配
    centos 安装 epel
    ubuntu jdk安装
    add_header Access-Control-Allow-Origin $http_Origin always;
    111
  • 原文地址:https://www.cnblogs.com/lls1350767625/p/7757646.html
Copyright © 2020-2023  润新知