控制台程序,上一条博文(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)的更多相关文章

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

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

  2. Java基础之写文件——将素数写入文件中(PrimesToFile)

    控制台程序,计算素数.创建文件路径.写文件. import static java.lang.Math.ceil; import static java.lang.Math.sqrt; import ...

  3. Java基础之写文件——在通道写入过程中的缓冲区状态(BufferStateTrace)

    控制台程序,在Junk目录中将字符串“Garbage in, garbage out\n”写入到名为charData.txt的文件中. import static java.nio.file.Stan ...

  4. Java基础之写文件——使用Formatter对象加载缓冲区(UsingAFormatter)

    控制台程序,使用Formatter对象将写入文件的数据准备好. 使用Formatter对象的format()方法,将数据值格式化到视图缓冲区charBuf中. import static java.n ...

  5. Java基础之写文件——将多个字符串写入到文件中(WriteProverbs)

    控制台程序,将一系列有用的格言写入到文件中. 本例使用通道把不同长度的字符串写入到文件中,为了方便从文件中恢复字符串,将每个字符串的长度写入到文件中紧靠字符串本身前面的位置,这可以告知在读取字符串之前 ...

  6. Java基础之写文件——使用多个视图缓冲区(PrimesToFile2)

    控制台程序.本例将对应于每个素数的数据以三个连续数据项的形式写入: 1.以二进制值表示的字符串长度值(最好是整型,但本例使用double类型): 2.素数值的字符串表示”Prime=nnn“,其中数字 ...

  7. Java基础之写文件——使用带缓冲的Writer写文件(WriterOutputToFile)

    控制台程序,将一列字符串写入到文件中. import java.io.*; import java.nio.file.*; import java.nio.charset.Charset; publi ...

  8. Java基础之写文件——创建通道并且写文件(TryChannel)

    控制台程序,创建一个文件并且使用通道将一些文本写入到这个文件中. import static java.nio.file.StandardOpenOption.*; import java.nio.c ...

  9. Java基础之写文件——通过缓冲流写文件(StreamOutputToFile)

    控制台程序,生成一些二进制整型值并且将它们写入到文件中. import java.nio.file.*; import java.nio.*; import java.io.*; public cla ...

随机推荐

  1. 【HAPPY FOREST】用Unreal Engine4绘制实时CG影像

    用Unreal Engine绘制实时CG影像 近年来,对实时CG的关心热度越来越高,但要想弥补与预渲染方式的差异并不是那么容易.这里就有影像业界的先锋进行挑战的MARZA ANIMATION PLAN ...

  2. 【翻译】Kinect v2程序设计(C++) Color篇

    Kinect SDK v2预览版,获取数据的基本流程的说明.以及取得Color图像的示例程序的介绍. 上一节,是关于当前型号Kinect for Windows(后面称作Kinect v1)和次世代型 ...

  3. PHP程序员必须清楚的问题汇总

    PHP程序员必须清楚的问题汇总 投稿:hebedich 字体:[增加 减小] 类型:转载   这篇文章主要介绍了PHP程序员必须清楚的问题汇总,需要的朋友可以参考下     你是否正在准备寻找一份PH ...

  4. ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

    https://en.wikipedia.org/wiki/Base64 The Base64 index table: Value Char   Value Char   Value Char   ...

  5. IIS7 .NET Runtime version 2.0.50727.5420 - 执行引擎错误(000007FEE77AAF0E) (80131506)

    装完系统,配置完IIS,发现.NET程序报503错误,出错后连接池自动关闭 这个程序是需要连接access数据库的,打开系统日志发现错误如下: 错误应用程序名称: w3wp.exe,版本: 7.5.7 ...

  6. SQuirreL 连接 hive

    软件安装版本: hadoop-2.5.1 hbase-0.98.12.1-hadoop2 apache-hive-1.2.1-bin SQuirreL SQL Client3.7 集成步骤: 1. S ...

  7. Qt调用Server SQL中的存储过程

    Server SQL中的存储过程如下: CREATE procedure PINSERTPC @pcnum int, @pcname varchar(50), @pctype int, @ipaddr ...

  8. FastDFS分布式文件系统安装与使用(单节点)

    http://blog.csdn.net/xyang81/article/details/52837974 http://download.csdn.net/detail/xyang81/966749 ...

  9. Compiling Inkscape on Windows

    http://wiki.inkscape.org/wiki/index.php/Compiling_Inkscape_on_Windows http://www.oschina.net/news/80 ...

  10. readonly=“readonly”与readonly=“true”

    <input id="u" readonly /> <input id="u" readonly="readonly" / ...