用java写程序使double 型数组中保存有如下数据:1.23,69.88,34.45,67.98,2345.67。将数据以二进制形式保存到文件中去。
时间: 2024-03-05 17:51:18 浏览: 65
以二进制方式存储的java程序
可以按照以下步骤进行:
1. 导入 java.io 包中的 FileOutputStream 类:
```java
import java.io.FileOutputStream;
import java.io.IOException;
```
2. 创建一个 double 数组并初始化:
```java
double[] data = {1.23, 69.88, 34.45, 67.98, 2345.67};
```
3. 创建一个 FileOutputStream 对象并以二进制写入模式打开它:
```java
FileOutputStream out = new FileOutputStream("data.bin");
```
4. 循环遍历数组,将每个 double 值以二进制形式写入文件中:
```java
for (double d : data) {
byte[] bytes = new byte[8];
long bits = Double.doubleToLongBits(d);
for (int i = 0; i < 8; i++) {
bytes[i] = (byte) ((bits >> (i * 8)) & 0xff);
}
out.write(bytes);
}
```
5. 关闭文件:
```java
out.close();
```
完整代码如下:
```java
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
double[] data = {1.23, 69.88, 34.45, 67.98, 2345.67};
FileOutputStream out = new FileOutputStream("data.bin");
for (double d : data) {
byte[] bytes = new byte[8];
long bits = Double.doubleToLongBits(d);
for (int i = 0; i < 8; i++) {
bytes[i] = (byte) ((bits >> (i * 8)) & 0xff);
}
out.write(bytes);
}
out.close();
}
}
```
阅读全文