文件的输入流

不管是字节流或者字符流,在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("\n Bytes read:" + count);//output the count
    } catch(IOException e) {
        System.out.println("Error -- " + e.toString());
    }
}
}

转载来自:http://www.cnblogs.com/gride-glory/p/7719075.html

转载于:https://www.cnblogs.com/lls1350767625/p/7757646.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值