Java基础之写文件——使用多个视图缓冲区(PrimesToFile2)
控制台程序。本例将对应于每个素数的数据以三个连续数据项的形式写入:
1、以二进制值表示的字符串长度值(最好是整型,但本例使用double类型);
2、素数值的字符串表示”Prime=nnn“,其中数字的位数明显是变化的;
3、将素数以long类型的二进制表示。
基本策略是,创建一个字节缓冲区,之后创建一系列将三种不同类型数据映射到其中的视图缓冲区。一种简单的方法是每次写入一个素数的数据。
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 PrimesToFile2 {
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","primes.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 = 100; // Byte buffer size
try (WritableByteChannel channel = Files.newByteChannel(file, EnumSet.of(WRITE, CREATE))){
ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
DoubleBuffer doubleBuf = buf.asDoubleBuffer();
buf.position(8);
CharBuffer charBuf = buf.asCharBuffer();
LongBuffer longBuf = null;
String primeStr = null; for (long prime : primes) {
primeStr = "prime = " + prime; // Create the string
doubleBuf.put(0,(double)primeStr.length()); // Store the string length
charBuf.put(primeStr); // Store the string
buf.position(2*charBuf.position() + 8); // Position for 3rd buffer
longBuf = buf.asLongBuffer(); // Create the buffer
longBuf.put(prime); // Store the binary long value
buf.position(buf.position() + 8); // Set position after last value
buf.flip(); // and flip
channel.write(buf); // Write the buffer as before buf.clear();
doubleBuf.clear();
charBuf.clear();
}
System.out.println("File written is " + ((FileChannel)channel).size() + " bytes.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java基础之写文件——使用多个视图缓冲区(PrimesToFile2)的更多相关文章
- Java基础之写文件——将素数写入文件中(PrimesToFile)
控制台程序,计算素数.创建文件路径.写文件. import static java.lang.Math.ceil; import static java.lang.Math.sqrt; import ...
- Java基础之写文件——缓冲区中的多条记录(PrimesToFile3)
控制台程序,上一条博文(PrimesToFile2)每次将一个素数写入到文件中,所以效率不是很高.最好是使用更大的缓冲区并加载多个素数. 本例重复使用三个不同的视图缓冲区加载字节缓冲区并尽可能加入更多 ...
- Java基础之写文件——使用Formatter对象加载缓冲区(UsingAFormatter)
控制台程序,使用Formatter对象将写入文件的数据准备好. 使用Formatter对象的format()方法,将数据值格式化到视图缓冲区charBuf中. import static java.n ...
- Java基础之写文件——将多个字符串写入到文件中(WriteProverbs)
控制台程序,将一系列有用的格言写入到文件中. 本例使用通道把不同长度的字符串写入到文件中,为了方便从文件中恢复字符串,将每个字符串的长度写入到文件中紧靠字符串本身前面的位置,这可以告知在读取字符串之前 ...
- Java基础之写文件——从多个缓冲区写(GatheringWrite)
控制台程序,使用单个写操作将数据从多个缓冲区按顺序传输到文件,这称为集中写(GatheringWrite)操作.这个功能的优势是能够避免在将信息写入到文件中之前将信息复制到单个缓冲区中.从每个缓冲区写 ...
- Java基础之写文件——在通道写入过程中的缓冲区状态(BufferStateTrace)
控制台程序,在Junk目录中将字符串“Garbage in, garbage out\n”写入到名为charData.txt的文件中. import static java.nio.file.Stan ...
- 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 ...
随机推荐
- TCP移动端跟服务器数据交互
同一台笔记本下的客户端和服务端 TCPClient 客户端: // RootViewController.h#import <UIKit/UIKit.h>#import "As ...
- 使用photoshop,把图片背景变成透明
鄙人使用的是photoshop CS6,win7系统,好了废话不多说,我们开始吧 1.打开photoshop,选择一个要编辑的图片 2.在右下角的图层面板上用鼠标左键快速双击背景图层为图片解锁 3.在 ...
- Oracle数据库常用命令
导出表数据 exp user/pwd@dbname file=filename.dmp tables=tbl_name rows=y indexes=n triggers=n grants=n 导入表 ...
- LR中获取当前系统时间方法
方法一:使用loadrunner的参数化获取当前时间使用lr的参数化,非常方便,对lr熟悉的各位朋友也能马上上手,时间格式也有很多,可以自由选择.步骤:1.将复制给aa的值参数化2.选中abc,使用右 ...
- miniproject black jack--Fail
第一部分 下载这个小项目的程序模板并回顾card类的定义.这个类已经执行了所以你的任务是自己熟悉下代码.开始,通过粘贴card类定义到程序模板中并验证我们的代码如预期那样工作. 实现“__init__ ...
- w-WAITING---
<p id="w_last" style="color: red; font-size: 6em;">w-WAITING---</p>& ...
- Linux - full name of command
pwd: print working directory cd: change directory ls: list ps: process status su: switch user mv: mo ...
- The world beyond batch: Streaming 101
https://www.oreilly.com/ideas/the-world-beyond-batch-streaming-101 https://www.oreilly.com/ideas/the ...
- 原生js实现跑马灯抽奖效果
目前好多的微信活动都有一些抽奖活动,其中就有跑马灯. <!DOCTYPE html> <html> <head> <title>跑马灯效果</ti ...
- CLR调试报错“Visual Studio远程调试监视器 (MSVSMON.EXE) 的 64 位版本无法调试 32 位进程或 32 位转储。请改用 32 位版本”的解决
Win7 64位电脑上进行visual studio的数据库项目的CLR存储过程进行调试时,报错: ---------------------------Microsoft Visual Studio ...