Java基础之写文件——将素数写入文件中(PrimesToFile)

本文介绍了一个控制台程序,用于计算指定数量的素数,并将这些素数写入到文件中。程序通过遍历奇数,检查其是否为素数,然后将素数存储在数组中并最终写入文件。

控制台程序,计算素数、创建文件路径、写文件。

 1 import static java.lang.Math.ceil;
 2 import static java.lang.Math.sqrt;
 3 import static java.lang.Math.min;
 4 import static java.nio.file.StandardOpenOption.*;
 5 import java.nio.file.*;
 6 import java.nio.channels.*;
 7 import java.nio.*;
 8 import java.util.*;
 9 import java.io.IOException;
10 
11 public class PrimesToFile {
12   public static void main(String[] args) {
13     int primesRequired = 100;                                          // Default count
14     if (args.length > 0) {
15       try {
16         primesRequired = Integer.valueOf(args[0]).intValue();
17       } catch (NumberFormatException e) {
18         System.out.println("Prime count value invalid. Using default of " + primesRequired);
19       }
20     }
21 
22       long[] primes = new long[primesRequired];                        // Array to store primes
23       
24       getPrimes(primes);
25       Path file = createFilePath("Beginning Java Struff","primes.bin");
26       writePrimesFile(primes,file);
27     }
28       //Calculate enough primes to fill the array
29       private static long[] getPrimes(long[] primes) {
30           primes[0] = 2L;                                                  // Seed the first prime
31           primes[1] = 3L;                                                  // and the second
32           // Count of primes found ?up to now, which is also the array index
33           int count = 2;
34           // Next integer to be tested
35           long number = 5L;
36 
37           outer:
38           for (; count < primes.length; number += 2) {
39 
40             // The maximum divisor we need to try is square root of number
41             long limit = (long)ceil(sqrt((double)number));
42 
43             // Divide by all the primes we have up to limit
44             for (int i = 1 ; i < count && primes[i] <= limit ; ++i)
45               if (number % primes[i] == 0L)                                // Is it an exact divisor?
46                 continue outer;                                            // yes, try the next number
47 
48             primes[count++] = number;                                      // We got one!
49           }
50           return primes;
51         }
52     //Create the path for the named file in the specified directory
53     //in the user home directory
54     private static Path createFilePath(String directory, String fileName) {
55         Path file = Paths.get(System.getProperty("user.home")).resolve(directory).resolve(fileName);
56         try {
57           Files.createDirectories(file.getParent());                       // Make sure we have the directory
58         } catch (IOException e) {
59           e.printStackTrace();
60           System.exit(1);
61         }
62         System.out.println("New file is: " + file);
63         return file;
64     }
65     
66     //Write the array contents to file
67     private static void writePrimesFile(long[] primes, Path file) {
68         final int BUFFERSIZE = 100;                                        // Byte buffer size
69         try (WritableByteChannel channel = Files.newByteChannel(file, EnumSet.of(WRITE, CREATE))) {
70           ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
71           LongBuffer longBuf = buf.asLongBuffer();                         // View buffer for type long
72           int primesWritten = 0;                                           // Count of primes written to file
73           while (primesWritten < primes.length) {
74             longBuf.put(primes,                                            // Array to be written
75                         primesWritten,                                     // Index of 1st element to write
76                         min(longBuf.capacity(), primes.length - primesWritten));
77             buf.limit(8*longBuf.position());                               // Update byte buffer position
78             channel.write(buf);
79             primesWritten += longBuf.position();
80             longBuf.clear();
81             buf.clear();
82           }
83           System.out.println("File written is " + ((FileChannel)channel).size() + " bytes.");
84         } catch (IOException e) {
85           e.printStackTrace();
86         }
87     }
88 }

 

转载于:https://www.cnblogs.com/mannixiang/p/3386745.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值