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 ...
随机推荐
- js 获取checkbox选中项目
# //获取选中项 $('#submit').click(function () { var check_list = [] $("input[name='ck']:checked" ...
- mac下限速
sudo ipfw pipe 1 config bw 15KByte/s #设置带宽 sudo ipfw add 1 pipe 1 src-port 80 sudo ipfw add 1 pipe 1 ...
- php常用[字符串]函数
nl2br 功能:化换行符为<br> <?php $str = "cat isn't \n dog"; $result = nl2br($str); echo $ ...
- Two's complement
https://en.wikipedia.org/wiki/Two's_complement The two's-complement system has the advantage that th ...
- Delphi的哈希表(一)
哈希表是通过哈希值来访问的,通过一定的内存浪费获取检索速度,在检索项时是不需要逐一检索.在编程中有一定的好处. unit Unit1; interface uses Windows, Messages ...
- J2msi 自己制作的把exe打成安装包简易GUI程序(第二版 带DLL注册)
J2msi 自己制作的把exe打成安装包简易GUI程序(第二版 带DLL注册) 之前那一版本(http://www.cnblogs.com/rojas/p/4794684.html)没考虑 DLL 注 ...
- App Previews操作经验
App Previews操作经验 http://www.cocoachina.com/ios/20140924/9741.html http://www.cocoachina.com/bbs/read ...
- 低功耗蓝牙BLE [学习笔记]
手机设备会区分 "connecting" and "pairing" ,前者可以自动连接,后者则需要请求.BLE不再有pairing的麻烦,能直接连上目标设备, ...
- FastMM、FastCode、FastMove的使用(图文并茂)
FastMM是一个替换Embarcadero Delphi Win32应用程序的快速内存管理器,以及可以在多线程下使用,不容易产生内存碎片,并且无需使用外部DLL文件就可以支持共享内存. 使用方法:1 ...
- 比较java与c语言中数字转换成字符的不同
java java中将数字转换成字符非常方便,只要用一个"+"然后在跟一个空格行了.比如,你输入一个122 ,就会变成"122 ". import java.u ...