• Java基础之写文件——缓冲区中的多条记录(PrimesToFile3)


    控制台程序,上一条博文(PrimesToFile2)每次将一个素数写入到文件中,所以效率不是很高。最好是使用更大的缓冲区并加载多个素数。

    本例重复使用三个不同的视图缓冲区加载字节缓冲区并尽可能加入更多的素数,推荐使用这种方式。

     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 PrimesToFile3 {
    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","primesAgain.txt");
    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 = 1024;                                        // Byte buffer size
    69         try (WritableByteChannel channel = Files.newByteChannel( file, EnumSet.of(WRITE, CREATE))){
    70           ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
    71           String primeStr = null;
    72           int primesWritten = 0;
    73         while (primesWritten < primes.length) {
    74             while (primesWritten < primes.length) {
    75               primeStr = "prime = " + primes[primesWritten];
    76               if ((buf.position() + 2*primeStr.length() + 16) > buf.limit()) {
    77                 break;
    78               }
    79               buf.asDoubleBuffer().put(0, (double)primeStr.length());
    80               buf.position(buf.position() + 8);
    81               buf.position(buf.position() + 2*buf.asCharBuffer().put(primeStr).position());
    82               buf.asLongBuffer().put(primes[primesWritten++]);
    83               buf.position(buf.position() + 8);
    84             }
    85             buf.flip();
    86             channel.write(buf);
    87             buf.clear();
    88           }
    89          System.out.println("File written is " + ((FileChannel)channel).size() + " bytes.");
    90         } catch (IOException e) {
    91           e.printStackTrace();
    92         }
    93     }
    94 }
  • 相关阅读:
    ios des加密
    testng-注解之@BeforeGroups、@AfterGroups +分组测试
    testng -忽略测试
    testng -注解之@BeforeSuite、@AfterSuite
    jmeter创建测试计划,执行post请求
    jmeter进行压力测试
    jmeter在mac电脑上安装使用
    java -获取变量类型
    java中枚举类enum
    java的日期与时间,Date ,SImpleDateFormat(), Calendar
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3386796.html
Copyright © 2020-2023  润新知