Java基础之写文件——使用多个视图缓冲区(PrimesToFile2)

控制台程序。本例将对应于每个素数的数据以三个连续数据项的形式写入:

1、以二进制值表示的字符串长度值(最好是整型,但本例使用double类型);

2、素数值的字符串表示”Prime=nnn“,其中数字的位数明显是变化的;

3、将素数以long类型的二进制表示。

基本策略是,创建一个字节缓冲区,之后创建一系列将三种不同类型数据映射到其中的视图缓冲区。一种简单的方法是每次写入一个素数的数据。

 1 import static java.lang.Math.ceil;
 2 import static java.lang.Math.sqrt;
 3 import static java.lang.Math.min;
 4 import static java.nio.file.StandardOpenOption.*;
 5 import java.nio.file.*;
 6 import java.nio.channels.*;
 7 import java.nio.*;
 8 import java.util.*;
 9 import java.io.IOException;
10 
11 public class PrimesToFile2 {
12   public static void main(String[] args) {
13     int primesRequired = 100;                                          // Default count
14     if (args.length > 0) {
15       try {
16         primesRequired = Integer.valueOf(args[0]).intValue();
17       } catch (NumberFormatException e) {
18         System.out.println("Prime count value invalid. Using default of " + primesRequired);
19       }
20     }
21 
22       long[] primes = new long[primesRequired];                        // Array to store primes
23       
24       getPrimes(primes);
25       Path file = createFilePath("Beginning Java Struff","primes.txt");
26       writePrimesFile(primes,file);
27     }
28       //Calculate enough primes to fill the array
29       private static long[] getPrimes(long[] primes) {
30           primes[0] = 2L;                                                  // Seed the first prime
31           primes[1] = 3L;                                                  // and the second
32           // Count of primes found ?up to now, which is also the array index
33           int count = 2;
34           // Next integer to be tested
35           long number = 5L;
36 
37           outer:
38           for (; count < primes.length; number += 2) {
39 
40             // The maximum divisor we need to try is square root of number
41             long limit = (long)ceil(sqrt((double)number));
42 
43             // Divide by all the primes we have up to limit
44             for (int i = 1 ; i < count && primes[i] <= limit ; ++i)
45               if (number % primes[i] == 0L)                                // Is it an exact divisor?
46                 continue outer;                                            // yes, try the next number
47 
48             primes[count++] = number;                                      // We got one!
49           }
50           return primes;
51         }
52     //Create the path for the named file in the specified directory
53     //in the user home directory
54     private static Path createFilePath(String directory, String fileName) {
55         Path file = Paths.get(System.getProperty("user.home")).resolve(directory).resolve(fileName);
56         try {
57           Files.createDirectories(file.getParent());                       // Make sure we have the directory
58         } catch (IOException e) {
59           e.printStackTrace();
60           System.exit(1);
61         }
62         System.out.println("New file is: " + file);
63         return file;
64     }
65     
66     //Write the array contents to file
67     private static void writePrimesFile(long[] primes, Path file) {
68         final int BUFFERSIZE = 100;                                        // Byte buffer size
69         try (WritableByteChannel channel = Files.newByteChannel(file, EnumSet.of(WRITE, CREATE))){
70           ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
71           DoubleBuffer doubleBuf = buf.asDoubleBuffer();
72           buf.position(8);
73           CharBuffer charBuf = buf.asCharBuffer();
74           LongBuffer longBuf = null;
75           String primeStr = null;
76 
77         for (long prime : primes) {
78             primeStr = "prime = " + prime;                                 // Create the string
79             doubleBuf.put(0,(double)primeStr.length());                    // Store the string length
80             charBuf.put(primeStr);                                         // Store the string
81             buf.position(2*charBuf.position() + 8);                        // Position for 3rd buffer
82             longBuf = buf.asLongBuffer();                                  // Create the buffer
83             longBuf.put(prime);                                            // Store the binary long value
84             buf.position(buf.position() + 8);                              // Set position after last value
85             buf.flip();                                                    // and flip
86             channel.write(buf);                                            // Write the buffer as before
87 
88             buf.clear();
89             doubleBuf.clear();
90             charBuf.clear();
91         }
92           System.out.println("File written is " + ((FileChannel)channel).size() + " bytes.");
93         } catch (IOException e) {
94           e.printStackTrace();
95         }
96     }
97 }

 

转载于:https://www.cnblogs.com/mannixiang/p/3386776.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/408391.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

react学习(32)----onref

// 父组件 import React from react import Son from ./son import { Button } from antdclass Father extends React.Component {child: anyconstructor(props) {super(props)}sonRef (ref) > {this.child ref // 在这里拿到子组件的实例}clearSonInput () > {this.c…

每日一学:如何用matplotlib展示图片

点击上方“算法猿的成长“&#xff0c;关注公众号&#xff0c;选择加“星标“或“置顶”总第 130 篇文章&#xff0c;本文大约 1000 字&#xff0c;阅读大约需要 5 分钟前言今天简单介绍如何通过 matplotlib 展示图片&#xff0c;分为以下几种情况&#xff1a;直接用 matplotli…

Servlet 过滤器

一、过滤器介绍 在Servlet 2.3中定义了过滤器&#xff0c;它能够对Servlet容器的请求和响应进行检查和修改。 Servlet过滤器能够在Servlet被调用之前检查Request对象&#xff0c;并修改Request Header 和 Request内容。 Filter可以过滤Servlet&#xff0c;JSP&#xff0c;HTML。…

每日一学:如何读取网络图片

点击上方“算法猿的成长“&#xff0c;关注公众号&#xff0c;选择加“星标“或“置顶”总第 131 篇文章&#xff0c;本文大约 1300 字&#xff0c;阅读大约需要 3 分钟前言有时候我们需要读取的图片是网络上的图片&#xff0c;应该怎么操作呢&#xff1f;这里也是介绍两个常用…

Windows Phone 如何振动手机?

1. 导入命名空间。 using Windows.Phone.Devices.Notification; 2. 通过调用对 VibrationDevice 类的静态 GetDefault 方法获取对振动控制器的引用。 VibrationDevice vibrationDevice VibrationDevice.GetDefault(); 3. 通过调用 VibrationDevice 类的 Vibrate 方法开始振动。…

编写高效的PyTorch代码技巧(上)

点击上方“算法猿的成长“&#xff0c;关注公众号&#xff0c;选择加“星标“或“置顶”总第 132 篇文章&#xff0c;本文大约 7000 字&#xff0c;阅读大约需要 20 分钟原文&#xff1a;https://github.com/vahidk/EffectivePyTorch作者&#xff1a;vahidk前言这是一份 PyTorc…

react学习(35)----getFieldDecorator will override value

我在自定义组件中定义了value值&#xff0c;getFieldDecorator会覆盖我们定义的值&#xff0c; 需要添加默认值可以使用在getFieldDecorator的时候&#xff0c;设置initialValue&#xff0c; 删除在自定义组件中定义的value就可以了&#xff01;

【ATT】Reverse Nodes in k-Group

ListNode* reverseBetween(ListNode* prev,ListNode* next)//reverse prev->next, last->prev之间的链表{ListNode* last prev->next;ListNode* cur last->next;while(cur!next){last->next cur->next;cur->next prev->next;prev->next cur;cu…

编写高效的PyTorch代码技巧(下)

点击上方“算法猿的成长“&#xff0c;关注公众号&#xff0c;选择加“星标“或“置顶”总第 133 篇文章&#xff0c;本文大约 3000 字&#xff0c;阅读大约需要 15 分钟原文&#xff1a;https://github.com/vahidk/EffectivePyTorch作者&#xff1a;vahidk前言这是一份 PyTorc…

统计(1 - 2)

统计学基础定义 Statistics的前部分为“state”&#xff0c;政府&#xff0c;原由是统计是300年前被首次应用在政府部门统计人口出生和死亡信息的&#xff1b;如今的统计学早已被应用在各个专业领域&#xff1b; 统计学是用以收集数据、分析数据和数据推论的一组概念、原则和方…

2020年计算机视觉学习指南

点击上方“算法猿的成长“&#xff0c;关注公众号&#xff0c;选择加“星标“或“置顶”总第 134 篇文章&#xff0c;本文大约 3000 字&#xff0c;阅读大约需要 10 分钟原文&#xff1a;https://towardsdatascience.com/guide-to-learn-computer-vision-in-2020-36f19d92c934作…

是选择Keras还是PyTorch开始你的深度学习之旅呢?

点击上方“算法猿的成长“&#xff0c;关注公众号&#xff0c;选择加“星标“或“置顶”总第 135 篇文章&#xff0c;本文大约 7000 字&#xff0c;阅读大约需要 20 分钟原文&#xff1a;https://medium.com/karan_jakhar/keras-vs-pytorch-dilemma-dc434e5b5ae0作者&#xff1…

关于myeclipse打开jsp巨慢解决方案

作为企业级开发最流行的工具&#xff0c;用Myeclipse开发java web程序无疑是最合适的&#xff0c;java web前端采用jsp来显示&#xff0c;myeclipse默认打开jsp的视图有卡顿的现象&#xff0c;那么如何更改jsp默认的打开方式&#xff0c;让我们可以进行更快速的jsp开发呢? 简单…

event

听取了网友:kenwang的意见,我的Blog在记流水账啊,现在才发现我发表的都是代码,一个感想也没有,以后要慢慢改正。明天要培训公司的框架&#xff0c;后天要搬家&#xff0c;这个周未没有得休息。

60分钟快速入门PyTorch

点击上方“算法猿的成长“&#xff0c;关注公众号&#xff0c;选择加“星标“或“置顶”总第 136 篇文章&#xff0c;本文大约 26000 字&#xff0c;阅读大约需要 60 分钟PyTorch 是由 Facebook 开发&#xff0c;基于 Torch 开发&#xff0c;从并不常用的 Lua 语言转为 Python …

react学习(38)----react是什么

什么是组件&#xff1f; 官方定义&#xff1a;将一些简短、独立的代码片段组合成复杂的 UI 界面&#xff0c;这些代码片段被称作“组件”。 解读&#xff1a;我们可以理解为能够组成一个UI界面的每一个独立的代码片段&#xff0c;例如表单的代码集合&#xff0c;轮播图的代码集…

大端与小端

/*************************************大端与小端&#xff1a;与大端存储格式相反&#xff0c;在小端存储格式中&#xff0c;低地址中存放的是字数据的低字节&#xff0c;高地址存放的是字数据的高字节**************************************//*联合体union的存放顺序是所有…

react学习(39)----react中的Hello World

ReactDOM.render(<h1>Hello, world!</h1>,document.getElementById(root) ); 它将在页面上展示一个 “Hello, world!” 的标题。

[libGDX游戏开发教程]使用libGDX进行游戏开发(12)-Action动画

前文章节列表&#xff1a;使用libGDX进行游戏开发(11)-高级编程技巧 使用libGDX进行游戏开发(10)-音乐音效不求人&#xff0c;程序员也可以DIY 使用libGDX进行游戏开发(9)-场景过渡使用libGDX进行游戏开发(8)-没有美工的程序员&#xff0c;能够依赖的还有粒子系统 使用libGDX进…