控制台程序,计算素数、创建文件路径、写文件。

 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)的更多相关文章

  1. Java基础-IO流对象之随机访问文件(RandomAccessFile)

    Java基础-IO流对象之随机访问文件(RandomAccessFile) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.RandomAccessFile简介 此类的实例支持对 ...

  2. c文件二进制读取写入文件、c语言实现二进制(01)转化成txt格式文本、c读取文件名可变

    c语言实现二进制(01)转化成txt格式文本: 下面的程序只能实现ascall对应字符转换,如果文件内出现中文字符,则会出现错误. 本程序要自己创建个文本格式的输入文件a1.txt,编译后能将文本文件 ...

  3. Java基础之写文件——缓冲区中的多条记录(PrimesToFile3)

    控制台程序,上一条博文(PrimesToFile2)每次将一个素数写入到文件中,所以效率不是很高.最好是使用更大的缓冲区并加载多个素数. 本例重复使用三个不同的视图缓冲区加载字节缓冲区并尽可能加入更多 ...

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

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

  5. Java基础学习(六)-- 递归以及文件I/O流基础详解

    递归 1.递归的概念: 在函数自身内部,调用函数本身的方式,称为递归. 2.递归的注意事项:包括递进去,归出来两步.   即:首先依次执行[函数调自身语句]上半部分的代码,知道最里层.(递进去),然后 ...

  6. java基础十[包、Jar存档文件和部署](阅读Head First Java记录)

    将Java的class文件生成为可执行的Java应用程序.Java应用程序有三种:完全在本机执行的Jar(例如本机的GUI可执行程序):完全在服务器端远程执行的(例如浏览器来进行存取):介于两者之间的 ...

  7. 【Java基础 】Java7 NIO Files,Path 操作文件

    从Java1.0到1.3,我们在开发需要I/O支持的应用时,要面临以下问题: 没有数据缓冲区或通道的概念,开发人员要编程处理很多底层细节 I/O操作会被阻塞,扩展能力有限 所支持的字符集编码有限,需要 ...

  8. Java进阶(二十二)使用FileOutputStream写入文件

    Java使用FileOutputStream写入文件 绪 在Java中,文件输出流是一种用于处理原始二进制数据的字节流类.为了将数据写入到文件中,必须将数据转换为字节,并保存到文件.请参阅下面的完整的 ...

  9. [Java基础] 深入jar包:从jar包中读取资源文件

    转载: http://hxraid.iteye.com/blog/483115?page=3#comments 我们常常在代码中读取一些资源文件(比如图片,音乐,文本等等).在单独运行的时候这些简单的 ...

随机推荐

  1. 从 github 执行 git clone 一个大的项目时提示 error: RPC failed

    目前克隆一个比较大的项目,出现RPC failed的错误 Cloning into 'bigfiles'... remote: Counting objects: 190, done. remote: ...

  2. 基于LR的HTTP协议接口性能测试脚本实例

    背景介绍 XXX项目性能测试中新增业务场景:XX设备的在线激活,因为存在多用户同时在线激活,故需进行性能测试以确认后台服务器系统在多用并发时功能是否正常,性能指标是否满足规格要求.用户使用场景为用户通 ...

  3. 后台list 如何转换为json格式

    request.setCharacterEncoding("utf-8"); response.setCharacterEncoding( "UTF-8"); ...

  4. 四 mybatis开发dao的方法

    mybatis开发dao的方法 1.1     SqlSession使用范围 1.1.1     SqlSessionFactoryBuilder //以流的方式读取总的配置文件 Reader rea ...

  5. Java Messages Synchronous and Asynchronous

    //The Consumer Class Consumes Messages in a Synchronous Manner public class Consumer { public static ...

  6. Python中定义字符串

    字符串可以用''或者""括起来表示.如果字符串本身包含'怎么办?比如我们要表示字符串 I'm OK ,这时,可以用" "括起来表示: "I'm OK& ...

  7. java并发编程-线程池的使用

    参考文章:http://www.cnblogs.com/dolphin0520/p/3932921.html 深入剖析线程池实现原理 将从下面几个方面讲解: 1.线程池状态 2.任务的执行 3.线程池 ...

  8. 《linux内核设计与实现》读书笔记第五章——系统调用

    第5章 系统调用 操作系统提供接口主要是为了保证系统稳定可靠,避免应用程序恣意妄行. 5.1 与内核通信 系统调用在用户空间进程和硬件设备之间添加了一个中间层. 该层主要作用有三个: 为用户空间提供了 ...

  9. 【Android测试】【第二节】ADB——无线模式

    ◆版权声明:本文出自胖喵~的博客,转载必须注明出处.      转载请注明出处:http://www.cnblogs.com/by-dream/p/4635782.html 啰嗦两句啊.本来以为adb ...

  10. detailsview 样式小问题

    detailsview不显示表头,设置HeaderText=""就可以,不知道为什么,如果有值,其他方式都没有调好! 内网格显示为0,Gridlines="None&qu ...