FileInputStream类和FileOutputStream类用于从/向文件读取/写入字节。它们的所有方法都是从InputStream类和OutputStream类中继承的,没有引进新的方法。要构造一个FileInputStream对象,调用下列构造方法,如图所示(1-1如果企图给一个不存在的文件创建FileInputStream对象,将会发生java.io.FileNotFoundException异常。要构造一个不存在的文件创建FileInputStream对象,请用下列构造方法,如图(1-2)
如果文件不存在,就会创建一个新的文件,如果文件已经存在那么,上述两个构造方法将会删除文件的当前内容,要既保留文件所有的内容又可以追加新的内容,将后两个方法中的参数append置为true并调用它们。·I/O中几乎所有的方法都抛出异常java.ioException,所以必须在方法中声明抛出java.io.IOException,或者将代码放到try-catch块中。
import java.io.*;
public class TestFileStream{
public static void main(String[] args)throws IOException {
//Create an output stream to the file
FileOutputStream output =new FileOutputStream("temp.dat");
for (int i=1;i<=10;i++)
output.write(i);
//Close the output Stream for the File
output.close();
//Create an input stream for the File
FileInputStream input = new FileInputStream("temp.dat");
//Read values from the file
int value;
while ((value=input.read()) != -1)
System.out.print (value +"");
//Close the output stream
input.close();
}
}
以下程序用二进制I/O将1到10的10个字节值输出到名为temp.dat的文件中。再把它们从文件中读出来。
其中文件temp.dat创建一个FileoutputStream对象。For循环10个字节值写入文件,调用write(i)方法与调用write((byte) i)具有相同的功能 ,output.close()是关闭输出流,FileInputStream input = new FileInputStream("temp.dat");是给文件创建一个FileInputStream对象,while ((value=input.read()) != -1) System.out.print (value +"");是从文件读取字节值并在控制台上显示出来。 表达式(value=input.read()) != -1从input.read()中读取一个字节,将它赋值给value,并且验证它是否为-1,如果是-1的话那意味着文件尾
<注意>该例子中的temp.bat是一个二进制的文件。可以使用java中文件访问它,但是不能用文本查看阅读
运行结果如下