Java基础之写文件——将素数写入文件中(PrimesToFile)

时间:2021-10-22 19:23:56

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

 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语言实现二进制&lpar;01&rpar;转化成txt格式文本、c读取文件名可变

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

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

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

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

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

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

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

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

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

  7. 【Java基础 】Java7 NIO Files&comma;Path 操作文件

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

  8. Java进阶&lpar;二十二&rpar;使用FileOutputStream写入文件

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

  9. &lbrack;Java基础&rsqb; 深入jar包:从jar包中读取资源文件

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

随机推荐

  1. hibernate&plus;mysql的连接池配置

    1:连接池的必知概念    首先,我们还是老套的讲讲连接池的基本概念,概念理解清楚了,我们也知道后面是怎么回事了. 以前我们程序连接数据库的时候,每一次连接数据库都要一个连接,用完后再释放.如果频繁的 ...

  2. Laravel &lbrack;1045&rsqb; 解决方法 Access denied for user &&num;39&semi;homestead&&num;39&semi;&commat;&&num;39&semi;localhost&&num;39&semi;

    这几天学习Laravel框架遇到了数据库方面的问题. PDOException in Connector.php line 55:SQLSTATE[HY000] [1045] Access denie ...

  3. 170106、用9种办法解决 JS 闭包经典面试题之 for 循环取 i

    闭包 1.正确的说,应该是指一个闭包域,每当声明了一个函数,它就产生了一个闭包域(可以解释为每个函数都有自己的函数栈),每个闭包域(Function 对象)都有一个 function scope(不是 ...

  4. NAT123 解决80端口被封的问题

    使用的服务器不知什么原因80端口无法使用了,好像是被封了,用的移动的固定IP,移动线路一直是不稳定 关键是移动的回答竟然是找不到哪里封的 是不是被屏蔽了,无奈使用了NAT123做处理.试了下还是管用. ...

  5. C&plus;&plus; 转型

    1.const_static的使用场景:接收一个const对象,但是想改变对象内容,使用const_static去除对象的常量性,然后可以修改对象. 2.dynamic_static的使用场景:从子类 ...

  6. Java语言与JVM中的Lambda表达式全解

    Lambda表达式是自Java SE 5引入泛型以来最重大的Java语言新特性,本文是2012年度最后一期Java Magazine中的一篇文章,它介绍了Lamdba的设计初衷,应用场景与基本语法. ...

  7. 理解Python中的类对象、实例对象、属性、方法

    class Animal(object): # 类对象 age = 0 # 公有类属性 __like = None # 私有类属性 def __init__(self): # 魔法方法 self.na ...

  8. npm ERR&excl; code ENOENT

    npm ERR! path F:\VsCodeWorkspace\labWeb\front\LabWebAdminFrontEnd\node_modules\core-jsnpm ERR! code ...

  9. 在Win10 Anaconda中安装Tensorflow

    有需要的朋友可以参考一下 1.安装Anaconda 下载:https://www.continuum.io/downloads,我用的是Python 3.5 下载完以后,安装.   安装完以后,打开A ...

  10. Python报错:ImportError&colon; No module named src&period;data&lowbar;layer

    ImportError: No module named src.data_layer 解决方案: export PYTHONPATH=path/to/modules