Java基础之写文件——缓冲区中的多条记录(PrimesToFile3)
控制台程序,上一条博文(PrimesToFile2)每次将一个素数写入到文件中,所以效率不是很高。最好是使用更大的缓冲区并加载多个素数。
本例重复使用三个不同的视图缓冲区加载字节缓冲区并尽可能加入更多的素数,推荐使用这种方式。
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 PrimesToFile3 {
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","primesAgain.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) {
final int BUFFERSIZE = 1024; // Byte buffer size
try (WritableByteChannel channel = Files.newByteChannel( file, EnumSet.of(WRITE, CREATE))){
ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
String primeStr = null;
int primesWritten = 0;
while (primesWritten < primes.length) {
while (primesWritten < primes.length) {
primeStr = "prime = " + primes[primesWritten];
if ((buf.position() + 2*primeStr.length() + 16) > buf.limit()) {
break;
}
buf.asDoubleBuffer().put(0, (double)primeStr.length());
buf.position(buf.position() + 8);
buf.position(buf.position() + 2*buf.asCharBuffer().put(primeStr).position());
buf.asLongBuffer().put(primes[primesWritten++]);
buf.position(buf.position() + 8);
}
buf.flip();
channel.write(buf);
buf.clear();
}
System.out.println("File written is " + ((FileChannel)channel).size() + " bytes.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java基础之写文件——缓冲区中的多条记录(PrimesToFile3)的更多相关文章
- Java基础之写文件——从多个缓冲区写(GatheringWrite)
控制台程序,使用单个写操作将数据从多个缓冲区按顺序传输到文件,这称为集中写(GatheringWrite)操作.这个功能的优势是能够避免在将信息写入到文件中之前将信息复制到单个缓冲区中.从每个缓冲区写 ...
- Java基础之写文件——将素数写入文件中(PrimesToFile)
控制台程序,计算素数.创建文件路径.写文件. import static java.lang.Math.ceil; import static java.lang.Math.sqrt; import ...
- Java基础之写文件——在通道写入过程中的缓冲区状态(BufferStateTrace)
控制台程序,在Junk目录中将字符串“Garbage in, garbage out\n”写入到名为charData.txt的文件中. import static java.nio.file.Stan ...
- Java基础之写文件——使用Formatter对象加载缓冲区(UsingAFormatter)
控制台程序,使用Formatter对象将写入文件的数据准备好. 使用Formatter对象的format()方法,将数据值格式化到视图缓冲区charBuf中. import static java.n ...
- Java基础之写文件——将多个字符串写入到文件中(WriteProverbs)
控制台程序,将一系列有用的格言写入到文件中. 本例使用通道把不同长度的字符串写入到文件中,为了方便从文件中恢复字符串,将每个字符串的长度写入到文件中紧靠字符串本身前面的位置,这可以告知在读取字符串之前 ...
- Java基础之写文件——使用多个视图缓冲区(PrimesToFile2)
控制台程序.本例将对应于每个素数的数据以三个连续数据项的形式写入: 1.以二进制值表示的字符串长度值(最好是整型,但本例使用double类型): 2.素数值的字符串表示”Prime=nnn“,其中数字 ...
- Java基础之写文件——使用带缓冲的Writer写文件(WriterOutputToFile)
控制台程序,将一列字符串写入到文件中. import java.io.*; import java.nio.file.*; import java.nio.charset.Charset; publi ...
- Java基础之写文件——创建通道并且写文件(TryChannel)
控制台程序,创建一个文件并且使用通道将一些文本写入到这个文件中. import static java.nio.file.StandardOpenOption.*; import java.nio.c ...
- Java基础之写文件——通过缓冲流写文件(StreamOutputToFile)
控制台程序,生成一些二进制整型值并且将它们写入到文件中. import java.nio.file.*; import java.nio.*; import java.io.*; public cla ...
随机推荐
- unity中Debug输出控制
1 需求: (1)选择在界面.console中输出,并且能够设置保存到文档 (2)控制debug是否输出,可以在debug模式下输出,release模式下不输出 2 参考: 谢谢雨松同学的博客:htt ...
- java--字符串替换replace,replaceAll,replaceFirst
1.字符串替换,replace string s="abcdfersabcdsgacabc"; 将字符串中的abc替换成bdf s.replace("abc", ...
- Amoeba基本配置
Amoeba安装及读写分离配置一.amoeba简介官网:http://docs.hexnova.com/amoeba/index.html二.Centos下安装jdk1.yum 安装1.6版本jdk2 ...
- endsWith和startsWith同样效果其他形式的写法(2016.1.12)
//判断以什么开始startWith str = "abcdef"; //用其他的形式写的startsWith if(str.indexOf("abc")==0 ...
- Turing Test
Computer Science An Overview _J. Glenn Brookshear _11th Edition In the past the Turing test (propose ...
- Artificial Intelligence Research Methodologies 人工智能研究方法
Computer Science An Overview _J. Glenn Brookshear _11th Edition To appreciate the field of artificia ...
- Types of compression algorithms
http://www.html5rocks.com/en/tutorials/speed/img-compression/ Types of compression algorithms There ...
- svn 入门
SVN版本:1.5 及更新版本 名词说明: WC:Working Copy 你的工作区 Versioned:受控的:受版本控制的 SVN是什么? SVN是开源的版本控制系统. 比CVS更多的特性.一个 ...
- This application failed to start because it could not find or load the Qt platform plugin "xcb".
1. copy libQt5DBus.so.5 2. add QT_PLUGIN_PATH blog.csdn.net/windows_nt/article/details/242 ...
- gtd好文两篇收藏
http://www.jianshu.com/p/bf5e8a9761f5 http://blog.sina.com.cn/s/blog_4e0f66b80100m73i.html