• Java基础之写文件——从多个缓冲区写(GatheringWrite)


    控制台程序,使用单个写操作将数据从多个缓冲区按顺序传输到文件,这称为集中写(GatheringWrite)操作。这个功能的优势是能够避免在将信息写入到文件中之前将信息复制到单个缓冲区中。从每个缓冲区写入到文件中的数据有这个缓冲区的位置和限制决定。

    本例会将字符串长度、字符串本身以及二进制素数值设置到单独的字节缓冲区中,另外还会将素数字符串作为本地编码的字节写入。

     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 GatheringWrite {
    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","GatheringWritePrimes.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) {      // Byte buffer size
    68         try (GatheringByteChannel channel = (FileChannel)(Files.newByteChannel(file, EnumSet.of(WRITE, CREATE)))){
    69           ByteBuffer[] buffers = new ByteBuffer[3];                        // Array of buffer references
    70           buffers[0] = ByteBuffer.allocate(8);                             // To hold a double value
    71           buffers[2] = ByteBuffer.allocate(8);                             // To hold a long value
    72 
    73           String primeStr = null;
    74           for (long prime : primes) {
    75             primeStr = "prime = " + prime;
    76             buffers[0].putDouble((double) primeStr.length()).flip();
    77 
    78             // Create the second buffer to accommodate the string
    79             buffers[1] = ByteBuffer.allocate(primeStr.length());
    80             buffers[1].put(primeStr.getBytes()).flip(); //String类中的getBytes()方法使用具体环境中设置的默认Charset将字符串的字符转换为字节
    81             //buffers[1] = ByteBuffer.wrap(primeStr.length());
    82 
    83             buffers[2].putLong(prime).flip();
    84             channel.write(buffers);
    85             buffers[0].clear();
    86             buffers[2].clear();
    87           }
    88          System.out.println("File written is " + ((FileChannel)channel).size() + " bytes.");
    89         } catch (IOException e) {
    90           e.printStackTrace();
    91         }
    92     }
    93 }
  • 相关阅读:
    推荐一个很好得电子书下载网站
    C# 线程手册 第四章 线程设计原则 管道线程模型
    C# 线程手册 第六章 线程调试与跟踪
    C# 线程手册 第五章 扩展多线程应用程序 剖析ThreadPool 类
    C# 线程手册 第六章 线程调试与跟踪 代码跟踪
    C# 线程手册 第五章 多线程应用程序 .NET 中的扩展性
    C# 线程手册 第五章 扩展多线程应用程序 CLR 和 线程
    C# 线程手册 第五章 扩展多线程应用程序 什么是线程池
    C# 线程手册 第五章 多线程应用程序 一个多线程微软消息队列(MSMQ)监听器
    C# 线程手册 第六章 线程调试与跟踪 使用不同的监听器程序
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3386835.html
Copyright © 2020-2023  润新知