不管是字节流或者字符流,在java中他们使用的过程都很相似。对于一个输入流:
文件输入流可以使用构造方法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
原文:http://www.cnblogs.com/lls1350767625/p/7757646.html