Java基础之写文件——将素数写入文件中(PrimesToFile)
控制台程序,计算素数、创建文件路径、写文件。
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 PrimesToFile {
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.bin");
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);
LongBuffer longBuf = buf.asLongBuffer(); // View buffer for type long
int primesWritten = 0; // Count of primes written to file
while (primesWritten < primes.length) {
longBuf.put(primes, // Array to be written
primesWritten, // Index of 1st element to write
min(longBuf.capacity(), primes.length - primesWritten));
buf.limit(8*longBuf.position()); // Update byte buffer position
channel.write(buf);
primesWritten += longBuf.position();
longBuf.clear();
buf.clear();
}
System.out.println("File written is " + ((FileChannel)channel).size() + " bytes.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java基础之写文件——将素数写入文件中(PrimesToFile)的更多相关文章
- Java基础-IO流对象之随机访问文件(RandomAccessFile)
Java基础-IO流对象之随机访问文件(RandomAccessFile) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.RandomAccessFile简介 此类的实例支持对 ...
- c文件二进制读取写入文件、c语言实现二进制(01)转化成txt格式文本、c读取文件名可变
c语言实现二进制(01)转化成txt格式文本: 下面的程序只能实现ascall对应字符转换,如果文件内出现中文字符,则会出现错误. 本程序要自己创建个文本格式的输入文件a1.txt,编译后能将文本文件 ...
- Java基础之写文件——缓冲区中的多条记录(PrimesToFile3)
控制台程序,上一条博文(PrimesToFile2)每次将一个素数写入到文件中,所以效率不是很高.最好是使用更大的缓冲区并加载多个素数. 本例重复使用三个不同的视图缓冲区加载字节缓冲区并尽可能加入更多 ...
- Java基础之写文件——使用Formatter对象加载缓冲区(UsingAFormatter)
控制台程序,使用Formatter对象将写入文件的数据准备好. 使用Formatter对象的format()方法,将数据值格式化到视图缓冲区charBuf中. import static java.n ...
- Java基础学习(六)-- 递归以及文件I/O流基础详解
递归 1.递归的概念: 在函数自身内部,调用函数本身的方式,称为递归. 2.递归的注意事项:包括递进去,归出来两步. 即:首先依次执行[函数调自身语句]上半部分的代码,知道最里层.(递进去),然后 ...
- java基础十[包、Jar存档文件和部署](阅读Head First Java记录)
将Java的class文件生成为可执行的Java应用程序.Java应用程序有三种:完全在本机执行的Jar(例如本机的GUI可执行程序):完全在服务器端远程执行的(例如浏览器来进行存取):介于两者之间的 ...
- 【Java基础 】Java7 NIO Files,Path 操作文件
从Java1.0到1.3,我们在开发需要I/O支持的应用时,要面临以下问题: 没有数据缓冲区或通道的概念,开发人员要编程处理很多底层细节 I/O操作会被阻塞,扩展能力有限 所支持的字符集编码有限,需要 ...
- Java进阶(二十二)使用FileOutputStream写入文件
Java使用FileOutputStream写入文件 绪 在Java中,文件输出流是一种用于处理原始二进制数据的字节流类.为了将数据写入到文件中,必须将数据转换为字节,并保存到文件.请参阅下面的完整的 ...
- [Java基础] 深入jar包:从jar包中读取资源文件
转载: http://hxraid.iteye.com/blog/483115?page=3#comments 我们常常在代码中读取一些资源文件(比如图片,音乐,文本等等).在单独运行的时候这些简单的 ...
随机推荐
- in_array效率问题以及解决办法
先将要对比的数组中的 键 和 值 设置成一样 然后用isset() 进行对比,存在则删除
- 20个C语言中常用宏定义总结
01: 防止一个头文件被重复包含 #ifndef COMDEF_H#define COMDEF_H//头文件内容#endif 02: 重新定义一些类型防止由于各种平台和编译器的不同,而产生的类型字节数 ...
- PDO操作
1.创建实例与取结果集 <? $db = new PDO('mysql:host=localhost;dbname=test', $user, $pass); $rs = $db->que ...
- MVC3中几个小知识点
1.ViewBag.Name~ViewBag.name等价,即不区分大小写.在此小心,下次见到不要奇怪,不过最好还是写成一样的比较好. 2.JS字符串不允许有换行符,\'等字符,需提前处理.
- ubuntu Nodejs和npm的安装
cnpm install -g XXX errors : npm i --registry=https://registry.npm.taobao.org 标签: nodejsnpm 20 ...
- TEST指令
In the x86 assembly language, the TEST instruction performs a bitwise AND on two operands. The flags ...
- Cocos2d-JS轻量级开发
官方提供了另外一种使用cocos2d js的方式,更适合web开发者,只要引用一个js就可以了 1.下载Cocos2d-JS Lite Version(去下载>>) 下载下来的将是一个完整 ...
- 关于android获得设备宽高
传统的办法: DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(d ...
- [LeetCode]题解(python):037-Sudoku Solver
题目来源 https://leetcode.com/problems/sudoku-solver/ Write a program to solve a Sudoku puzzle by fillin ...
- Eclipse 常用整理
1.编译 eclipse默认是修改程序后自动编译的,如果不能自动编译,你可以查看project->build automatically选项是否被选中. 手动编译整个工程,可以使用Project ...