控制台程序,上一条博文(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. FAQ&ubuntu12.04 gedit 打开 txt 文件乱码

    ubuntu12.04 gedit 打开 windows 分区中的 txt 文件乱码,是因为 ubuntu 和 windows 两个系统的编码不同.解决办法:终端里依次输入以下2 条命令即可: 代码: ...

  2. C#winform中使用控件的Dock属性进行布局

    想要实现如下布局,可以通过设置控件的Dock属性达到效果 1.拖放一个panel控件一个label控件(放在panel中)和一个treeView控件到TestForm中 2.设置panel的Dock属 ...

  3. C#winform控制textbox输入只能为数字

    添加keyPress事件,控制键盘输入只能是自然数: /// <summary> /// 控制键盘输入只能是自然数 /// </summary> /// <param n ...

  4. Alternative Representations for 4-Bit Integers

    COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION

  5. a computer-centered view of information systems to a database-centered view

    Code.Complete.Second.Edition 2004 Bachman compared the Ptolemaic-to-Copernican change in astronomy t ...

  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. java开发bug 在启动Tomcat 6.0时发现第一条信息便是

    MyEclipse 8.5 + tomcat6 + jdk 1.8 启动的时候报错: The APR based Apache Tomcat Native library which allows o ...

  8. phpcms v9 模板调用代码大全

    另:每个栏目会对应当前所选模型的三个模板文件:  这些模板文件所在位置:phpcms/templates/default/content/ 目录下,如果想修改模板文件,只需要到此目录下找到对应的模板文 ...

  9. 在MyEclipse下创建Java Web项目 入门(图文并茂)经典教程

    http://jijiaa12345.iteye.com/blog/1739754 在MyEclipse下创建Java Web项目 入门(图文并茂)经典教程 本文是一篇在Myeclipse下构建Jav ...

  10. os相关方法总结

    __file__表示当前文件 os.path.dirname表示当前文件所在路径的父路径 os.pardir表示当前文件名 os.path.join表示合并 os.path.abspath表示绝对路径