使用数据字节流将指定范围内的所有素数写入整形类型文件
import java.io.*;
public class Writeron
{
private String filename;
public Writeron(String filename)
{
this.filename = filename;
}
public void writeToFile() throws IOException
{
FileOutputStream fout = new FileOutputStream(this.filename);
DataOutputStream dout = new DataOutputStream(fout);
int i,j,flag;
for(i=2;i<100;i++){
flag=1;
for(j=2;j<i;j++){
if(i%j==0){
flag=0;
}
}
if(flag==1){
dout.writeInt(i);
}
}
dout.close(); //先关闭数据流
fout.close(); //再关闭文件流
}
public void readFromFile() throws IOException //从指定文件中读取整数
{
FileInputStream fin = new FileInputStream(this.filename);
DataInputStream din = new DataInputStream(fin);
System.out.println(this.filename+":");
while (true) //输入流未结束时
try
{
int i = din.readInt(); //从输入流中读取一个整数
System.out.print(i+" ");
}
catch (EOFException e)
{
break;
}
din.close(); //先关闭数据流
fin.close(); //再关闭文件流
}
public static void main(String args[]) throws IOException
{
Writeron afile = new Writeron("sushu.dat");
afile.writeToFile();
afile.readFromFile();
}
}
/*
程序运行结果如下:
sushu.dat:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
程序设计说明如下:
1、readInt()方法到达输入流末尾时,抛出EOFException异常。
*/