Java基础之写文件——从多个缓冲区写(GatheringWrite)
2013-10-24 21:27
489 查看
控制台程序,使用单个写操作将数据从多个缓冲区按顺序传输到文件,这称为集中写(GatheringWrite)操作。这个功能的优势是能够避免在将信息写入到文件中之前将信息复制到单个缓冲区中。从每个缓冲区写入到文件中的数据有这个缓冲区的位置和限制决定。
本例会将字符串长度、字符串本身以及二进制素数值设置到单独的字节缓冲区中,另外还会将素数字符串作为本地编码的字节写入。
本例会将字符串长度、字符串本身以及二进制素数值设置到单独的字节缓冲区中,另外还会将素数字符串作为本地编码的字节写入。
import static java.lang.Math.ceil; import static java.lang.Math.sqrt; import static java.lang.Math.min; import static java.nio.file.StandardOpenOption.*; import java.nio.file.*; import java.nio.channels.*; import java.nio.*; import java.util.*; import java.io.IOException; public class GatheringWrite { public static void main(String[] args) { int primesRequired = 100; // Default count if (args.length > 0) { try { primesRequired = Integer.valueOf(args[0]).intValue(); } catch (NumberFormatException e) { System.out.println("Prime count value invalid. Using default of " + primesRequired); } } long[] primes = new long[primesRequired]; // Array to store primes getPrimes(primes); Path file = createFilePath("Beginning Java Struff","GatheringWritePrimes.txt"); writePrimesFile(primes,file); } //Calculate enough primes to fill the array private static long[] getPrimes(long[] primes) { primes[0] = 2L; // Seed the first prime primes[1] = 3L; // and the second // Count of primes found ?up to now, which is also the array index int count = 2; // Next integer to be tested long number = 5L; outer: for (; count < primes.length; number += 2) { // The maximum divisor we need to try is square root of number long limit = (long)ceil(sqrt((double)number)); // Divide by all the primes we have up to limit for (int i = 1 ; i < count && primes[i] <= limit ; ++i) if (number % primes[i] == 0L) // Is it an exact divisor? continue outer; // yes, try the next number primes[count++] = number; // We got one! } return primes; } //Create the path for the named file in the specified directory //in the user home directory private static Path createFilePath(String directory, String fileName) { Path file = Paths.get(System.getProperty("user.home")).resolve(directory).resolve(fileName); try { Files.createDirectories(file.getParent()); // Make sure we have the directory } catch (IOException e) { e.printStackTrace(); System.exit(1); } System.out.println("New file is: " + file); return file; } //Write the array contents to file private static void writePrimesFile(long[] primes, Path file) { // Byte buffer size try (GatheringByteChannel channel = (FileChannel)(Files.newByteChannel(file, EnumSet.of(WRITE, CREATE)))){ ByteBuffer[] buffers = new ByteBuffer[3]; // Array of buffer references buffers[0] = ByteBuffer.allocate(8); // To hold a double value buffers[2] = ByteBuffer.allocate(8); // To hold a long value String primeStr = null; for (long prime : primes) { primeStr = "prime = " + prime; buffers[0].putDouble((double) primeStr.length()).flip(); // Create the second buffer to accommodate the string buffers[1] = ByteBuffer.allocate(primeStr.length()); buffers[1].put(primeStr.getBytes()).flip(); //String类中的getBytes()方法使用具体环境中设置的默认Charset将字符串的字符转换为字节 //buffers[1] = ByteBuffer.wrap(primeStr.length()); buffers[2].putLong(prime).flip(); channel.write(buffers); buffers[0].clear(); buffers[2].clear(); } System.out.println("File written is " + ((FileChannel)channel).size() + " bytes."); } catch (IOException e) { e.printStackTrace(); } } }
相关文章推荐
- java concurrency in practice读书笔记----第三章
- 解决Eclipse无法打开“Failed to load the JNI shared library”
- C#中委托的理解(方便Java的童孩们理解)
- java的学习技巧方案分析!
- java的工作解析!
- ubuntu 13.04 install jdk 7
- java的学习方案!
- DK1.5中的线程池(java.util.concurrent.ThreadPoolExecutor)使用简介
- JMX “javax.management.NotCompliantMBeanException” 异常解决
- spring源码分析------IO(1)
- Unable to start activity : java .lang.nullPointException
- Java基础之写文件——缓冲区中的多条记录(PrimesToFile3)
- morphia更新数据库时,报错:Caused by: java.lang.IllegalArgumentException: can't serialize class
- Java路径问题最终解决方案
- Java Hour1
- Java Hour2
- java的图片,动画功能
- java socket编程
- Java基础之写文件——使用多个视图缓冲区(PrimesToFile2)
- 关于java 中流读取时遇到的阻塞和返回-1的问题探究