Java基础之写文件——从多个缓冲区写(GatheringWrite)
控制台程序,使用单个写操作将数据从多个缓冲区按顺序传输到文件,这称为集中写(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基础之写文件——从多个缓冲区写(GatheringWrite)的更多相关文章
- Java基础之读文件——使用输入流读取二进制文件(StreamInputFromFile)
控制台程序,读取Java基础之读文件部分(StreamOutputToFile)写入的50个fibonacci数字. import java.nio.file.*; import java.nio.* ...
- Java基础之读文件——使用通道读取混合数据2(ReadPrimesMixedData2)
控制台程序,本例读取Java基础之写文件部分(PrimesToFile2)写入的Primes.txt. 方法二:设置一个任意容量的.大小合适的字节缓冲区并且使用来自文件的字节进行填充.然后整理出缓冲区 ...
- Java基础之读文件——使用通道读取混合数据1(ReadPrimesMixedData)
控制台程序,本例读取Java基础之写文件部分(PrimesToFile2)写入的Primes.txt. 方法一:可以在第一个读操作中读取字符串的长度,然后再将字符串和二进制素数值读入到文本中.这种方式 ...
- Java基础之读文件——使用通道读二进制数据(ReadPrimes)
控制台程序,本例读取Java基础之写文件部分(PrimesToFile)写入的primes.bin. import java.nio.file.*; import java.nio.*; import ...
- Java基础之读文件——从文件中读取文本(ReadAString)
控制台程序,使用通道从缓冲区获取数据,读取Java基础之写文件(BufferStateTrace)写入的charData.txt import java.nio.file.*; import java ...
- Java基础之读文件——使用缓冲读取器读取文件(ReaderInputFromFile)
控制台程序,本例读取Java基础之写文件部分(WriterOutputToFile)写入的Saying.txt. import java.io.*; import java.nio.file.*; i ...
- Java基础知识之文件操作
流与文件的操作在编程中经常遇到,与C语言只有单一类型File*即可工作良好不同,Java拥有一个包含各种流类型的流家族,其数量超过60个!当然我们没必要去记住这60多个类或接口以及它们的层次结构,理解 ...
- java基础之读取文件方法大全
1.按字节读取文件内容2.按字符读取文件内容3.按行读取文件内容 4.随机读取文件内容 public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如 ...
- Java基础知识系列——文件操作
对文件进行操作在编程中比较少用,但是我最近有一个任务需要用到对文件操作. 对文件有如下操作形式: 1.创建新的文件(夹) File fileName = new File("C:/myfil ...
随机推荐
- thinkphp四种url访问方式详解
本文实例分析了thinkphp的四种url访问方式.分享给大家供大家参考.具体分析如下: 一.什么是MVC thinkphp的MVC模式非常灵活,即使只有三个中和一个也可以运行. M -Model 编 ...
- 浅析php学习的路线图
一直都想走上码农的道路,奈何当年没有学好.一直与码农无缘.现在又想做一些码农就下了一套某个培训机构的php视频来看.希望能走上码农的道路 1.php初级教程 初级教程主要的页面设置的,就是 h ...
- 数据库留言板例题:session和cookie区别
session和cookie区别: <?php session_start(); //session_start();必须写在所有的php代码前边 ?> <!DOCTYPE html ...
- Apache的HBase与cdh的hue集成(不建议不同版本之间的集成)
1.修改hue的配置文件hue.ini [hbase] # Use full hostname with security. hbase_clusters=(Cluster|linux-hadoop3 ...
- php---实现保留小数点后两位
PHP 中的 round() 函数可以实现 round() 函数对浮点数进行四舍五入. round(x,prec) 参数说明x 可选.规定要舍入的数字.prec 可选.规定小数点后的位数. 返回将 x ...
- JNI字段描述符(转)
转载自http://fgsink.blog.163.com/blog/static/16716997020124310169911/ “([Ljava/lang/String;)V” 它是一种对函数返 ...
- django internal search
最近改进了项目中的站内搜索的功能,增加了全文索引,提升了搜索速度.因为项目框架是django,所以采用django+haystack+pyelasticsearch+elasticsearch的方式实 ...
- 【上手centos】二、C/C++的编译与运行
尝试了一下运行C/C++程序,觉得最好还是记下来吧,毕竟也算是从不知到已知呢么. 我用sublime写了2个程序,test.c和test.cpp,分别是C程序和C++程序 step1:编译: #gcc ...
- OC的内存管理
摘自:http://blog.csdn.net/hahahacff/article/details/39839571 OC内存管理 一.基本原理 (一)为什么要进行内存管理. 由于移动设备的内存极其有 ...
- Android Keycode详解
用JAVA写appium的testcase时,想用Android自带的物理返回键,网上找了下分享给大家. import io.appium.java_client.android.AndroidKey ...