?? primesfile.java
字號:
import java.io.*;
public class PrimesFile
{
RandomAccessFile raf;
public static void main(String args[]) throws IOException
{
(new PrimesFile()). createprime(100);
}
public void createprime(int max) throws IOException
{
raf=new RandomAccessFile("primes.bin","rw");//創建文件對象
raf.seek(0); //文件指針為0
raf.writeInt(2); //寫入整型
int k=3;
while (k<=max)
{
if (isPrime(k))
raf.writeInt(k);
k = k+2;
}
output(max);
raf.close(); //關閉文件
}
public boolean isPrime(int k) throws IOException
{
int i=0,j;
boolean yes = true;
try
{
raf.seek(0);
int count = (int)(raf.length()/4); //返回文件字節長度
while ((i<=count) && yes)
{
if (k % raf.readInt()==0) //讀取整型
yes = false;
else
i++;
raf.seek(i*4); //移動文件指針
}
} catch(EOFException e) { } //捕獲到達文件尾異常
return yes;
}
public void output(int max) throws IOException
{
try
{
raf.seek(0);
System.out.println("[2.."+max+"]中有 "+
(raf.length()/4)+" 個素數:");
for (int i=0;i<(int)(raf.length()/4);i++)
{
raf.seek(i*4);
System.out.print(raf.readInt()+" ");
if ((i+1)%10==0) System.out.println();
}
} catch(EOFException e) { }
System.out.println();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -